OSDN Git Service

Merge branch 'cleanup-code-analyzer-errors'
[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.Runtime.CompilerServices;
33 using System.Runtime.Serialization;
34 using System.Runtime.Serialization.Json;
35 using System.Text;
36 using System.Text.RegularExpressions;
37 using System.Threading;
38 using System.Threading.Tasks;
39 using System.Web;
40 using System.Xml;
41 using System.Xml.Linq;
42 using System.Xml.XPath;
43 using System;
44 using System.Reflection;
45 using System.Collections.Generic;
46 using System.Drawing;
47 using System.Windows.Forms;
48 using OpenTween.Api;
49 using OpenTween.Connection;
50
51 namespace OpenTween
52 {
53     public class Twitter : IDisposable
54     {
55         #region Regexp from twitter-text-js
56
57         // The code in this region code block incorporates works covered by
58         // the following copyright and permission notices:
59         //
60         //   Copyright 2011 Twitter, Inc.
61         //
62         //   Licensed under the Apache License, Version 2.0 (the "License"); you
63         //   may not use this work except in compliance with the License. You
64         //   may obtain a copy of the License in the LICENSE file, or at:
65         //
66         //   http://www.apache.org/licenses/LICENSE-2.0
67         //
68         //   Unless required by applicable law or agreed to in writing, software
69         //   distributed under the License is distributed on an "AS IS" BASIS,
70         //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
71         //   implied. See the License for the specific language governing
72         //   permissions and limitations under the License.
73
74         //Hashtag用正規表現
75         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";
76         private const string NON_LATIN_HASHTAG_CHARS = @"\u0400-\u04ff\u0500-\u0527\u1100-\u11ff\u3130-\u3185\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF";
77         //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";
78         private const string CJ_HASHTAG_CHARACTERS = @"\u30A1-\u30FA\u30FC\u3005\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u309A\u3400-\u4DBF\p{IsCJKUnifiedIdeographs}";
79         private const string HASHTAG_BOUNDARY = @"^|$|\s|「|」|。|\.|!";
80         private const string HASHTAG_ALPHA = "[a-z_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
81         private const string HASHTAG_ALPHANUMERIC = "[a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
82         private const string HASHTAG_TERMINATOR = "[^a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
83         public const string HASHTAG = "(" + HASHTAG_BOUNDARY + ")(#|#)(" + HASHTAG_ALPHANUMERIC + "*" + HASHTAG_ALPHA + HASHTAG_ALPHANUMERIC + "*)(?=" + HASHTAG_TERMINATOR + "|" + HASHTAG_BOUNDARY + ")";
84         //URL正規表現
85         private const string url_valid_preceding_chars = @"(?:[^A-Za-z0-9@@$##\ufffe\ufeff\uffff\u202a-\u202e]|^)";
86         public const string url_invalid_without_protocol_preceding_chars = @"[-_./]$";
87         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";
88         private const string url_valid_domain_chars = @"[^" + url_invalid_domain_chars + "]";
89         private const string url_valid_subdomain = @"(?:(?:" + url_valid_domain_chars + @"(?:[_-]|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
90         private const string url_valid_domain_name = @"(?:(?:" + url_valid_domain_chars + @"(?:-|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
91         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]|$))";
92         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]|$))";
93         private const string url_valid_punycode = @"(?:xn--[0-9a-z]+)";
94         private const string url_valid_domain = @"(?<domain>" + url_valid_subdomain + "*" + url_valid_domain_name + "(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + ")|" + url_valid_punycode + ")";
95         public const string url_valid_ascii_domain = @"(?:(?:[a-z0-9" + LATIN_ACCENTS + @"]+)\.)+(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + "|" + url_valid_punycode + ")";
96         public const string url_invalid_short_domain = "^" + url_valid_domain_name + url_valid_CCTLD + "$";
97         private const string url_valid_port_number = @"[0-9]+";
98
99         private const string url_valid_general_path_chars = @"[a-z0-9!*';:=+,.$/%#\[\]\-_~|&" + LATIN_ACCENTS + "]";
100         private const string url_balance_parens = @"(?:\(" + url_valid_general_path_chars + @"+\))";
101         private const string url_valid_path_ending_chars = @"(?:[+\-a-z0-9=_#/" + LATIN_ACCENTS + "]|" + url_balance_parens + ")";
102         private const string pth = "(?:" +
103             "(?:" +
104                 url_valid_general_path_chars + "*" +
105                 "(?:" + url_balance_parens + url_valid_general_path_chars + "*)*" +
106                 url_valid_path_ending_chars +
107                 ")|(?:@" + url_valid_general_path_chars + "+/)" +
108             ")";
109         private const string qry = @"(?<query>\?[a-z0-9!?*'();:&=+$/%#\[\]\-_.,~|]*[a-z0-9_&=#/])?";
110         public const string rgUrl = @"(?<before>" + url_valid_preceding_chars + ")" +
111                                     "(?<url>(?<protocol>https?://)?" +
112                                     "(?<domain>" + url_valid_domain + ")" +
113                                     "(?::" + url_valid_port_number + ")?" +
114                                     "(?<path>/" + pth + "*)?" +
115                                     qry +
116                                     ")";
117
118         #endregion
119
120         /// <summary>
121         /// Twitter API のステータスページのURL
122         /// </summary>
123         public const string ServiceAvailabilityStatusUrl = "https://status.io.watchmouse.com/7617";
124
125         /// <summary>
126         /// ツイートへのパーマリンクURLを判定する正規表現
127         /// </summary>
128         public static readonly Regex StatusUrlRegex = new Regex(@"https?://([^.]+\.)?twitter\.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)/status(es)?/(?<StatusId>[0-9]+)(/photo)?", RegexOptions.IgnoreCase);
129
130         /// <summary>
131         /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
132         /// </summary>
133         public static readonly Regex ThirdPartyStatusUrlRegex = new Regex(@"https?://(?:[^.]+\.)?(?:
134   favstar\.fm/users/[a-zA-Z0-9_]+/status/       # Favstar
135 | favstar\.fm/t/                                # Favstar (short)
136 | aclog\.koba789\.com/i/                        # aclog
137 | frtrt\.net/solo_status\.php\?status=          # RtRT
138 )(?<StatusId>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
139
140         /// <summary>
141         /// DM送信かどうかを判定する正規表現
142         /// </summary>
143         public static readonly Regex DMSendTextRegex = new Regex(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
144
145         public TwitterConfiguration Configuration { get; private set; }
146
147         delegate void GetIconImageDelegate(PostClass post);
148         private readonly object LockObj = new object();
149         private ISet<long> followerId = new HashSet<long>();
150         private bool _GetFollowerResult = false;
151         private long[] noRTId = new long[0];
152         private bool _GetNoRetweetResult = false;
153
154         //プロパティからアクセスされる共通情報
155         private string _uname;
156
157         private bool _readOwnPost;
158         private List<string> _hashList = new List<string>();
159
160         //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
161         private long minHomeTimeline = long.MaxValue;
162         private long minMentions = long.MaxValue;
163         private long minDirectmessage = long.MaxValue;
164         private long minDirectmessageSent = long.MaxValue;
165
166         //private FavoriteQueue favQueue;
167
168         private HttpTwitter twCon = new HttpTwitter();
169
170         //private List<PostClass> _deletemessages = new List<PostClass>();
171
172         public Twitter()
173         {
174             this.Configuration = TwitterConfiguration.DefaultConfiguration();
175         }
176
177         public TwitterApiAccessLevel AccessLevel
178         {
179             get
180             {
181                 return MyCommon.TwitterApiInfo.AccessLevel;
182             }
183         }
184
185         protected void ResetApiStatus()
186         {
187             MyCommon.TwitterApiInfo.Reset();
188         }
189
190         public void Authenticate(string username, string password)
191         {
192             this.ResetApiStatus();
193
194             HttpStatusCode res;
195             var content = "";
196             try
197             {
198                 res = twCon.AuthUserAndPass(username, password, ref content);
199             }
200             catch(Exception ex)
201             {
202                 throw new WebApiException("Err:" + ex.Message, ex);
203             }
204
205             this.CheckStatusCode(res, content);
206
207             _uname = username.ToLowerInvariant();
208             if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
209         }
210
211         public string StartAuthentication()
212         {
213             //OAuth PIN Flow
214             this.ResetApiStatus();
215             try
216             {
217                 string pinPageUrl = null;
218                 var res = twCon.AuthGetRequestToken(ref pinPageUrl);
219                 if (!res)
220                     throw new WebApiException("Err:Failed to access auth server.");
221
222                 return pinPageUrl;
223             }
224             catch (Exception ex)
225             {
226                 throw new WebApiException("Err:Failed to access auth server.", ex);
227             }
228         }
229
230         public void Authenticate(string pinCode)
231         {
232             this.ResetApiStatus();
233
234             HttpStatusCode res;
235             try
236             {
237                 res = twCon.AuthGetAccessToken(pinCode);
238             }
239             catch (Exception ex)
240             {
241                 throw new WebApiException("Err:Failed to access auth acc server.", ex);
242             }
243
244             this.CheckStatusCode(res, null);
245
246             _uname = Username.ToLowerInvariant();
247             if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
248         }
249
250         public void ClearAuthInfo()
251         {
252             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
253             this.ResetApiStatus();
254             twCon.ClearAuthInfo();
255         }
256
257         public void VerifyCredentials()
258         {
259             HttpStatusCode res;
260             var content = "";
261             try
262             {
263                 res = twCon.VerifyCredentials(ref content);
264             }
265             catch (Exception ex)
266             {
267                 throw new WebApiException("Err:" + ex.Message, ex);
268             }
269
270             this.CheckStatusCode(res, content);
271
272             try
273             {
274                 var user = TwitterUser.ParseJson(content);
275
276                 this.twCon.AuthenticatedUserId = user.Id;
277                 this.UpdateUserStats(user);
278             }
279             catch (SerializationException ex)
280             {
281                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
282                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
283             }
284         }
285
286         public void Initialize(string token, string tokenSecret, string username, long userId)
287         {
288             //OAuth認証
289             if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
290             {
291                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
292             }
293             this.ResetApiStatus();
294             twCon.Initialize(token, tokenSecret, username, userId);
295             _uname = username.ToLowerInvariant();
296             if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
297         }
298
299         public string PreProcessUrl(string orgData)
300         {
301             int posl1;
302             var posl2 = 0;
303             //var IDNConveter = new IdnMapping();
304             var href = "<a href=\"";
305
306             while (true)
307             {
308                 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
309                 {
310                     var urlStr = "";
311                     // IDN展開
312                     posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
313                     posl1 += href.Length;
314                     posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
315                     urlStr = orgData.Substring(posl1, posl2 - posl1);
316
317                     if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
318                         && !urlStr.StartsWith("https://", StringComparison.Ordinal)
319                         && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
320                     {
321                         continue;
322                     }
323
324                     var replacedUrl = MyCommon.IDNEncode(urlStr);
325                     if (replacedUrl == null) continue;
326                     if (replacedUrl == urlStr) continue;
327
328                     orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
329                     posl2 = 0;
330                 }
331                 else
332                 {
333                     break;
334                 }
335             }
336             return orgData;
337         }
338
339         private string GetPlainText(string orgData)
340         {
341             return WebUtility.HtmlDecode(Regex.Replace(orgData, "(?<tagStart><a [^>]+>)(?<text>[^<]+)(?<tagEnd></a>)", "${text}"));
342         }
343
344         // htmlの簡易サニタイズ(詳細表示に不要なタグの除去)
345
346         private string SanitizeHtml(string orgdata)
347         {
348             var retdata = orgdata;
349
350             retdata = Regex.Replace(retdata, "<(script|object|applet|image|frameset|fieldset|legend|style).*" +
351                 "</(script|object|applet|image|frameset|fieldset|legend|style)>", "", RegexOptions.IgnoreCase);
352
353             retdata = Regex.Replace(retdata, "<(frame|link|iframe|img)>", "", RegexOptions.IgnoreCase);
354
355             return retdata;
356         }
357
358         private string AdjustHtml(string orgData)
359         {
360             var retStr = orgData;
361             //var m = Regex.Match(retStr, "<a [^>]+>[#|#](?<1>[a-zA-Z0-9_]+)</a>");
362             //while (m.Success)
363             //{
364             //    lock (LockObj)
365             //    {
366             //        _hashList.Add("#" + m.Groups(1).Value);
367             //    }
368             //    m = m.NextMatch;
369             //}
370             retStr = Regex.Replace(retStr, "<a [^>]*href=\"/", "<a href=\"https://twitter.com/");
371             retStr = retStr.Replace("<a href=", "<a target=\"_self\" href=");
372             retStr = Regex.Replace(retStr, @"(\r\n?|\n)", "<br>"); // CRLF, CR, LF は全て <br> に置換する
373
374             //半角スペースを置換(Thanks @anis774)
375             var ret = false;
376             do
377             {
378                 ret = EscapeSpace(ref retStr);
379             } while (!ret);
380
381             return SanitizeHtml(retStr);
382         }
383
384         private bool EscapeSpace(ref string html)
385         {
386             //半角スペースを置換(Thanks @anis774)
387             var isTag = false;
388             for (int i = 0; i < html.Length; i++)
389             {
390                 if (html[i] == '<')
391                 {
392                     isTag = true;
393                 }
394                 if (html[i] == '>')
395                 {
396                     isTag = false;
397                 }
398
399                 if ((!isTag) && (html[i] == ' '))
400                 {
401                     html = html.Remove(i, 1);
402                     html = html.Insert(i, "&nbsp;");
403                     return false;
404                 }
405             }
406             return true;
407         }
408
409         private struct PostInfo
410         {
411             public string CreatedAt;
412             public string Id;
413             public string Text;
414             public string UserId;
415             public PostInfo(string Created, string IdStr, string txt, string uid)
416             {
417                 CreatedAt = Created;
418                 Id = IdStr;
419                 Text = txt;
420                 UserId = uid;
421             }
422             public bool Equals(PostInfo dst)
423             {
424                 if (this.CreatedAt == dst.CreatedAt && this.Id == dst.Id && this.Text == dst.Text && this.UserId == dst.UserId)
425                 {
426                     return true;
427                 }
428                 else
429                 {
430                     return false;
431                 }
432             }
433         }
434
435         static private PostInfo _prev = new PostInfo("", "", "", "");
436         private bool IsPostRestricted(TwitterStatus status)
437         {
438             var _current = new PostInfo("", "", "", "");
439
440             _current.CreatedAt = status.CreatedAt;
441             _current.Id = status.IdStr;
442             if (status.Text == null)
443             {
444                 _current.Text = "";
445             }
446             else
447             {
448                 _current.Text = status.Text;
449             }
450             _current.UserId = status.User.IdStr;
451
452             if (_current.Equals(_prev))
453             {
454                 return true;
455             }
456             _prev.CreatedAt = _current.CreatedAt;
457             _prev.Id = _current.Id;
458             _prev.Text = _current.Text;
459             _prev.UserId = _current.UserId;
460
461             return false;
462         }
463
464         public void PostStatus(string postStr, long? reply_to, List<long> mediaIds = null)
465         {
466             this.CheckAccountState();
467
468             if (mediaIds == null &&
469                 Twitter.DMSendTextRegex.IsMatch(postStr))
470             {
471                 SendDirectMessage(postStr);
472                 return;
473             }
474
475             HttpStatusCode res;
476             var content = "";
477             try
478             {
479                 res = twCon.UpdateStatus(postStr, reply_to, mediaIds, ref content);
480             }
481             catch(Exception ex)
482             {
483                 throw new WebApiException("Err:" + ex.Message, ex);
484             }
485
486             // 投稿に成功していても404が返ることがあるらしい: https://dev.twitter.com/discussions/1213
487             if (res == HttpStatusCode.NotFound)
488                 return;
489
490             this.CheckStatusCode(res, content);
491
492             TwitterStatus status;
493             try
494             {
495                 status = TwitterStatus.ParseJson(content);
496             }
497             catch(SerializationException ex)
498             {
499                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
500                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
501             }
502             catch(Exception ex)
503             {
504                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
505                 throw new WebApiException("Err:Invalid Json!", content, ex);
506             }
507
508             this.UpdateUserStats(status.User);
509
510             if (IsPostRestricted(status))
511             {
512                 throw new WebApiException("OK:Delaying?");
513             }
514         }
515
516         public void PostStatusWithMedia(string postStr, long? reply_to, IMediaItem item)
517         {
518             this.CheckAccountState();
519
520             HttpStatusCode res;
521             var content = "";
522             try
523             {
524                 res = twCon.UpdateStatusWithMedia(postStr, reply_to, item, ref content);
525             }
526             catch(Exception ex)
527             {
528                 throw new WebApiException("Err:" + ex.Message, ex);
529             }
530
531             // 投稿に成功していても404が返ることがあるらしい: https://dev.twitter.com/discussions/1213
532             if (res == HttpStatusCode.NotFound)
533                 return;
534
535             this.CheckStatusCode(res, content);
536
537             TwitterStatus status;
538             try
539             {
540                 status = TwitterStatus.ParseJson(content);
541             }
542             catch(SerializationException ex)
543             {
544                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
545                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
546             }
547             catch(Exception ex)
548             {
549                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
550                 throw new WebApiException("Err:Invalid Json!", content, ex);
551             }
552
553             this.UpdateUserStats(status.User);
554
555             if (IsPostRestricted(status))
556             {
557                 throw new WebApiException("OK:Delaying?");
558             }
559         }
560
561         public void PostStatusWithMultipleMedia(string postStr, long? reply_to, IMediaItem[] mediaItems)
562         {
563             this.CheckAccountState();
564
565             if (Twitter.DMSendTextRegex.IsMatch(postStr))
566             {
567                 SendDirectMessage(postStr);
568                 return;
569             }
570
571             var mediaIds = new List<long>();
572
573             foreach (var item in mediaItems)
574             {
575                 var mediaId = UploadMedia(item);
576                 mediaIds.Add(mediaId);
577             }
578
579             if (mediaIds.Count == 0)
580                 throw new WebApiException("Err:Invalid Files!");
581
582             PostStatus(postStr, reply_to, mediaIds);
583         }
584
585         public long UploadMedia(IMediaItem item)
586         {
587             this.CheckAccountState();
588
589             HttpStatusCode res;
590             var content = "";
591             try
592             {
593                 res = twCon.UploadMedia(item, ref content);
594             }
595             catch (Exception ex)
596             {
597                 throw new WebApiException("Err:" + ex.Message, ex);
598             }
599
600             this.CheckStatusCode(res, content);
601
602             TwitterUploadMediaResult status;
603             try
604             {
605                 status = TwitterUploadMediaResult.ParseJson(content);
606             }
607             catch (SerializationException ex)
608             {
609                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
610                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
611             }
612             catch (Exception ex)
613             {
614                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
615                 throw new WebApiException("Err:Invalid Json!", content, ex);
616             }
617
618             return status.MediaId;
619         }
620
621         public void SendDirectMessage(string postStr)
622         {
623             this.CheckAccountState();
624             this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
625
626             var mc = Twitter.DMSendTextRegex.Match(postStr);
627
628             HttpStatusCode res;
629             var content = "";
630             try
631             {
632                 res = twCon.SendDirectMessage(mc.Groups["body"].Value, mc.Groups["id"].Value, ref content);
633             }
634             catch(Exception ex)
635             {
636                 throw new WebApiException("Err:" + ex.Message, ex);
637             }
638
639             this.CheckStatusCode(res, content);
640
641             TwitterDirectMessage status;
642             try
643             {
644                 status = TwitterDirectMessage.ParseJson(content);
645             }
646             catch(SerializationException ex)
647             {
648                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
649                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
650             }
651             catch(Exception ex)
652             {
653                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
654                 throw new WebApiException("Err:Invalid Json!", content, ex);
655             }
656
657             this.UpdateUserStats(status.Sender);
658         }
659
660         public void RemoveStatus(long id)
661         {
662             this.CheckAccountState();
663
664             HttpStatusCode res;
665             try
666             {
667                 res = twCon.DestroyStatus(id);
668             }
669             catch(Exception ex)
670             {
671                 throw new WebApiException("Err:" + ex.Message, ex);
672             }
673
674             this.CheckStatusCode(res, null);
675         }
676
677         public void PostRetweet(long id, bool read)
678         {
679             this.CheckAccountState();
680
681             //データ部分の生成
682             var target = id;
683             var post = TabInformations.GetInstance()[id];
684             if (post == null)
685             {
686                 throw new WebApiException("Err:Target isn't found.");
687             }
688             if (TabInformations.GetInstance()[id].RetweetedId != null)
689             {
690                 target = TabInformations.GetInstance()[id].RetweetedId.Value; //再RTの場合は元発言をRT
691             }
692
693             HttpStatusCode res;
694             var content = "";
695             try
696             {
697                 res = twCon.RetweetStatus(target, ref content);
698             }
699             catch(Exception ex)
700             {
701                 throw new WebApiException("Err:" + ex.Message, ex);
702             }
703
704             this.CheckStatusCode(res, content);
705
706             TwitterStatus status;
707             try
708             {
709                 status = TwitterStatus.ParseJson(content);
710             }
711             catch(SerializationException ex)
712             {
713                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
714                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
715             }
716             catch(Exception ex)
717             {
718                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
719                 throw new WebApiException("Err:Invalid Json!", content, ex);
720             }
721
722             //ReTweetしたものをTLに追加
723             post = CreatePostsFromStatusData(status);
724             if (post == null)
725                 throw new WebApiException("Invalid Json!", content);
726
727             //二重取得回避
728             lock (LockObj)
729             {
730                 if (TabInformations.GetInstance().ContainsKey(post.StatusId))
731                     return;
732             }
733             //Retweet判定
734             if (post.RetweetedId == null)
735                 throw new WebApiException("Invalid Json!", content);
736             //ユーザー情報
737             post.IsMe = true;
738
739             post.IsRead = read;
740             post.IsOwl = false;
741             if (_readOwnPost) post.IsRead = true;
742             post.IsDm = false;
743
744             TabInformations.GetInstance().AddPost(post);
745         }
746
747         public void RemoveDirectMessage(long id, PostClass post)
748         {
749             this.CheckAccountState();
750             this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
751
752             //if (post.IsMe)
753             //    _deletemessages.Add(post)
754             //}
755
756             HttpStatusCode res;
757             try
758             {
759                 res = twCon.DestroyDirectMessage(id);
760             }
761             catch(Exception ex)
762             {
763                 throw new WebApiException("Err:" + ex.Message, ex);
764             }
765
766             this.CheckStatusCode(res, null);
767         }
768
769         public void PostFollowCommand(string screenName)
770         {
771             this.CheckAccountState();
772
773             HttpStatusCode res;
774             var content = "";
775             try
776             {
777                 res = twCon.CreateFriendships(screenName, ref content);
778             }
779             catch(Exception ex)
780             {
781                 throw new WebApiException("Err:" + ex.Message, ex);
782             }
783
784             this.CheckStatusCode(res, content);
785         }
786
787         public void PostRemoveCommand(string screenName)
788         {
789             this.CheckAccountState();
790
791             HttpStatusCode res;
792             var content = "";
793             try
794             {
795                 res = twCon.DestroyFriendships(screenName, ref content);
796             }
797             catch(Exception ex)
798             {
799                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
800             }
801
802             this.CheckStatusCode(res, content);
803         }
804
805         public void PostCreateBlock(string screenName)
806         {
807             this.CheckAccountState();
808
809             HttpStatusCode res;
810             var content = "";
811             try
812             {
813                 res = twCon.CreateBlock(screenName, ref content);
814             }
815             catch(Exception ex)
816             {
817                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
818             }
819
820             this.CheckStatusCode(res, content);
821         }
822
823         public void PostDestroyBlock(string screenName)
824         {
825             this.CheckAccountState();
826
827             HttpStatusCode res;
828             var content = "";
829             try
830             {
831                 res = twCon.DestroyBlock(screenName, ref content);
832             }
833             catch(Exception ex)
834             {
835                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
836             }
837
838             this.CheckStatusCode(res, content);
839         }
840
841         public void PostReportSpam(string screenName)
842         {
843             this.CheckAccountState();
844
845             HttpStatusCode res;
846             var content = "";
847             try
848             {
849                 res = twCon.ReportSpam(screenName, ref content);
850             }
851             catch(Exception ex)
852             {
853                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
854             }
855
856             this.CheckStatusCode(res, content);
857         }
858
859         public TwitterFriendship GetFriendshipInfo(string screenName)
860         {
861             this.CheckAccountState();
862
863             HttpStatusCode res;
864             var content = "";
865             try
866             {
867                 res = twCon.ShowFriendships(_uname, screenName, ref content);
868             }
869             catch(Exception ex)
870             {
871                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
872             }
873
874             this.CheckStatusCode(res, content);
875
876             try
877             {
878                 return TwitterFriendship.ParseJson(content);
879             }
880             catch(SerializationException ex)
881             {
882                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
883                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
884             }
885             catch(Exception ex)
886             {
887                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
888                 throw new WebApiException("Err:Invalid Json!", content, ex);
889             }
890         }
891
892         public TwitterUser GetUserInfo(string screenName)
893         {
894             this.CheckAccountState();
895
896             HttpStatusCode res;
897             var content = "";
898             try
899             {
900                 res = twCon.ShowUserInfo(screenName, ref content);
901             }
902             catch(Exception ex)
903             {
904                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
905             }
906
907             this.CheckStatusCode(res, content);
908
909             try
910             {
911                 return TwitterUser.ParseJson(content);
912             }
913             catch (SerializationException ex)
914             {
915                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
916                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
917             }
918             catch (Exception ex)
919             {
920                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
921                 throw new WebApiException("Err:Invalid Json!", content, ex);
922             }
923         }
924
925         public int GetStatus_Retweeted_Count(long StatusId)
926         {
927             this.CheckAccountState();
928
929             HttpStatusCode res;
930             var content = "";
931             try
932             {
933                 res = twCon.ShowStatuses(StatusId, ref content);
934             }
935             catch (Exception ex)
936             {
937                 throw new WebApiException("Err:" + ex.Message, ex);
938             }
939
940             this.CheckStatusCode(res, content);
941
942             try
943             {
944                 var status = TwitterStatus.ParseJson(content);
945                 return status.RetweetCount;
946             }
947             catch (SerializationException ex)
948             {
949                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
950                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
951             }
952             catch (Exception ex)
953             {
954                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
955                 throw new WebApiException("Invalid Json!", content, ex);
956             }
957         }
958
959         public void PostFavAdd(long id)
960         {
961             this.CheckAccountState();
962
963             //if (this.favQueue == null) this.favQueue = new FavoriteQueue(this)
964
965             //if (this.favQueue.Contains(id)) this.favQueue.Remove(id)
966
967             HttpStatusCode res;
968             var content = "";
969             try
970             {
971                 res = twCon.CreateFavorites(id, ref content);
972             }
973             catch(Exception ex)
974             {
975                 //this.favQueue.Add(id)
976                 //return "Err:->FavoriteQueue:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")";
977                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
978             }
979
980             this.CheckStatusCode(res, content);
981
982             if (!RestrictFavCheck)
983                 return;
984
985             //http://twitter.com/statuses/show/id.xml APIを発行して本文を取得
986
987             try
988             {
989                 res = twCon.ShowStatuses(id, ref content);
990             }
991             catch(Exception ex)
992             {
993                 throw new WebApiException("Err:" + ex.Message, ex);
994             }
995
996             this.CheckStatusCode(res, content);
997
998             TwitterStatus status;
999             try
1000             {
1001                 status = TwitterStatus.ParseJson(content);
1002             }
1003             catch (SerializationException ex)
1004             {
1005                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1006                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1007             }
1008             catch (Exception ex)
1009             {
1010                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1011                 throw new WebApiException("Err:Invalid Json!", content, ex);
1012             }
1013             if (status.Favorited != true)
1014                 throw new WebApiException("NG(Restricted?)");
1015         }
1016
1017         public void PostFavRemove(long id)
1018         {
1019             this.CheckAccountState();
1020
1021             //if (this.favQueue == null) this.favQueue = new FavoriteQueue(this)
1022
1023             //if (this.favQueue.Contains(id))
1024             //    this.favQueue.Remove(id)
1025             //    return "";
1026             //}
1027
1028             HttpStatusCode res;
1029             var content = "";
1030             try
1031             {
1032                 res = twCon.DestroyFavorites(id, ref content);
1033             }
1034             catch(Exception ex)
1035             {
1036                 throw new WebApiException("Err:" + ex.Message, ex);
1037             }
1038
1039             this.CheckStatusCode(res, content);
1040         }
1041
1042         public TwitterUser PostUpdateProfile(string name, string url, string location, string description)
1043         {
1044             this.CheckAccountState();
1045
1046             HttpStatusCode res;
1047             var content = "";
1048             try
1049             {
1050                 res = twCon.UpdateProfile(name, url, location, description, ref content);
1051             }
1052             catch(Exception ex)
1053             {
1054                 throw new WebApiException("Err:" + ex.Message, content, ex);
1055             }
1056
1057             this.CheckStatusCode(res, content);
1058
1059             try
1060             {
1061                 return TwitterUser.ParseJson(content);
1062             }
1063             catch (SerializationException e)
1064             {
1065                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
1066                 MyCommon.TraceOut(ex);
1067                 throw ex;
1068             }
1069             catch (Exception e)
1070             {
1071                 var ex = new WebApiException("Err:Invalid Json!", content, e);
1072                 MyCommon.TraceOut(ex);
1073                 throw ex;
1074             }
1075         }
1076
1077         public void PostUpdateProfileImage(string filename)
1078         {
1079             this.CheckAccountState();
1080
1081             HttpStatusCode res;
1082             var content = "";
1083             try
1084             {
1085                 res = twCon.UpdateProfileImage(new FileInfo(filename), ref content);
1086             }
1087             catch(Exception ex)
1088             {
1089                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1090             }
1091
1092             this.CheckStatusCode(res, content);
1093         }
1094
1095         public string Username
1096         {
1097             get
1098             {
1099                 return twCon.AuthenticatedUsername;
1100             }
1101         }
1102
1103         public long UserId
1104         {
1105             get
1106             {
1107                 return twCon.AuthenticatedUserId;
1108             }
1109         }
1110
1111         public string Password
1112         {
1113             get
1114             {
1115                 return twCon.Password;
1116             }
1117         }
1118
1119         private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
1120         public static MyCommon.ACCOUNT_STATE AccountState
1121         {
1122             get
1123             {
1124                 return _accountState;
1125             }
1126             set
1127             {
1128                 _accountState = value;
1129             }
1130         }
1131
1132         public bool RestrictFavCheck { get; set; }
1133
1134 #region "バージョンアップ"
1135         public void GetTweenBinary(string strVer)
1136         {
1137             try
1138             {
1139                 //本体
1140                 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/Tween" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1141                                                     Path.Combine(MyCommon.settingPath, "TweenNew.exe")))
1142                 {
1143                     throw new WebApiException("Err:Download failed");
1144                 }
1145                 //英語リソース
1146                 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, "en")))
1147                 {
1148                     Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, "en"));
1149                 }
1150                 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenResEn" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1151                                                     Path.Combine(Path.Combine(MyCommon.settingPath, "en"), "Tween.resourcesNew.dll")))
1152                 {
1153                     throw new WebApiException("Err:Download failed");
1154                 }
1155                 //その他言語圏のリソース。取得失敗しても継続
1156                 //UIの言語圏のリソース
1157                 var curCul = "";
1158                 if (!Thread.CurrentThread.CurrentUICulture.IsNeutralCulture)
1159                 {
1160                     var idx = Thread.CurrentThread.CurrentUICulture.Name.LastIndexOf('-');
1161                     if (idx > -1)
1162                     {
1163                         curCul = Thread.CurrentThread.CurrentUICulture.Name.Substring(0, idx);
1164                     }
1165                     else
1166                     {
1167                         curCul = Thread.CurrentThread.CurrentUICulture.Name;
1168                     }
1169                 }
1170                 else
1171                 {
1172                     curCul = Thread.CurrentThread.CurrentUICulture.Name;
1173                 }
1174                 if (!string.IsNullOrEmpty(curCul) && curCul != "en" && curCul != "ja")
1175                 {
1176                     if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul)))
1177                     {
1178                         Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul));
1179                     }
1180                     if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1181                                                         Path.Combine(Path.Combine(MyCommon.settingPath, curCul), "Tween.resourcesNew.dll")))
1182                     {
1183                         //return "Err:Download failed";
1184                     }
1185                 }
1186                 //スレッドの言語圏のリソース
1187                 string curCul2;
1188                 if (!Thread.CurrentThread.CurrentCulture.IsNeutralCulture)
1189                 {
1190                     var idx = Thread.CurrentThread.CurrentCulture.Name.LastIndexOf('-');
1191                     if (idx > -1)
1192                     {
1193                         curCul2 = Thread.CurrentThread.CurrentCulture.Name.Substring(0, idx);
1194                     }
1195                     else
1196                     {
1197                         curCul2 = Thread.CurrentThread.CurrentCulture.Name;
1198                     }
1199                 }
1200                 else
1201                 {
1202                     curCul2 = Thread.CurrentThread.CurrentCulture.Name;
1203                 }
1204                 if (!string.IsNullOrEmpty(curCul2) && curCul2 != "en" && curCul2 != curCul)
1205                 {
1206                     if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul2)))
1207                     {
1208                         Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul2));
1209                     }
1210                     if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul2 + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1211                                                     Path.Combine(Path.Combine(MyCommon.settingPath, curCul2), "Tween.resourcesNew.dll")))
1212                     {
1213                         //return "Err:Download failed";
1214                     }
1215                 }
1216
1217                 //アップデータ
1218                 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenUp3.gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1219                                                     Path.Combine(MyCommon.settingPath, "TweenUp3.exe")))
1220                 {
1221                     throw new WebApiException("Err:Download failed");
1222                 }
1223                 //シリアライザDLL
1224                 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenDll" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1225                                                     Path.Combine(MyCommon.settingPath, "TweenNew.XmlSerializers.dll")))
1226                 {
1227                     throw new WebApiException("Err:Download failed");
1228                 }
1229             }
1230             catch (Exception ex)
1231             {
1232                 throw new WebApiException("Err:Download failed", ex);
1233             }
1234         }
1235 #endregion
1236
1237         public bool ReadOwnPost
1238         {
1239             get
1240             {
1241                 return _readOwnPost;
1242             }
1243             set
1244             {
1245                 _readOwnPost = value;
1246             }
1247         }
1248
1249         public int FollowersCount { get; private set; }
1250         public int FriendsCount { get; private set; }
1251         public int StatusesCount { get; private set; }
1252         public string Location { get; private set; } = "";
1253         public string Bio { get; private set; } = "";
1254
1255         /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
1256         private void UpdateUserStats(TwitterUser self)
1257         {
1258             this.FollowersCount = self.FollowersCount;
1259             this.FriendsCount = self.FriendsCount;
1260             this.StatusesCount = self.StatusesCount;
1261             this.Location = self.Location;
1262             this.Bio = self.Description;
1263         }
1264
1265         /// <summary>
1266         /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
1267         /// </summary>
1268         public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
1269         {
1270             return count >= 20 && count <= GetMaxApiResultCount(type);
1271         }
1272
1273         /// <summary>
1274         /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
1275         /// </summary>
1276         public static bool VerifyMoreApiResultCount(int count)
1277         {
1278             return count >= 20 && count <= 200;
1279         }
1280
1281         /// <summary>
1282         /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
1283         /// </summary>
1284         public static bool VerifyFirstApiResultCount(int count)
1285         {
1286             return count >= 20 && count <= 200;
1287         }
1288
1289         /// <summary>
1290         /// WORKERTYPEに応じた取得可能な最大件数を取得する
1291         /// </summary>
1292         public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
1293         {
1294             // 参照: REST APIs - 各endpointのcountパラメータ
1295             // https://dev.twitter.com/rest/public
1296             switch (type)
1297             {
1298                 case MyCommon.WORKERTYPE.Timeline:
1299                 case MyCommon.WORKERTYPE.Reply:
1300                 case MyCommon.WORKERTYPE.UserTimeline:
1301                 case MyCommon.WORKERTYPE.Favorites:
1302                 case MyCommon.WORKERTYPE.DirectMessegeRcv:
1303                 case MyCommon.WORKERTYPE.DirectMessegeSnt:
1304                 case MyCommon.WORKERTYPE.List:  // 不明
1305                     return 200;
1306
1307                 case MyCommon.WORKERTYPE.PublicSearch:
1308                     return 100;
1309
1310                 default:
1311                     throw new InvalidOperationException("Invalid type: " + type);
1312             }
1313         }
1314
1315         /// <summary>
1316         /// WORKERTYPEに応じた取得件数を取得する
1317         /// </summary>
1318         public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
1319         {
1320             if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
1321                 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
1322             {
1323                 return 20;
1324             }
1325
1326             if (SettingCommon.Instance.UseAdditionalCount)
1327             {
1328                 switch (type)
1329                 {
1330                     case MyCommon.WORKERTYPE.Favorites:
1331                         if (SettingCommon.Instance.FavoritesCountApi != 0)
1332                             return SettingCommon.Instance.FavoritesCountApi;
1333                         break;
1334                     case MyCommon.WORKERTYPE.List:
1335                         if (SettingCommon.Instance.ListCountApi != 0)
1336                             return SettingCommon.Instance.ListCountApi;
1337                         break;
1338                     case MyCommon.WORKERTYPE.PublicSearch:
1339                         if (SettingCommon.Instance.SearchCountApi != 0)
1340                             return SettingCommon.Instance.SearchCountApi;
1341                         break;
1342                     case MyCommon.WORKERTYPE.UserTimeline:
1343                         if (SettingCommon.Instance.UserTimelineCountApi != 0)
1344                             return SettingCommon.Instance.UserTimelineCountApi;
1345                         break;
1346                 }
1347                 if (more && SettingCommon.Instance.MoreCountApi != 0)
1348                 {
1349                     return Math.Min(SettingCommon.Instance.MoreCountApi, GetMaxApiResultCount(type));
1350                 }
1351                 if (startup && SettingCommon.Instance.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
1352                 {
1353                     return Math.Min(SettingCommon.Instance.FirstCountApi, GetMaxApiResultCount(type));
1354                 }
1355             }
1356
1357             // 上記に当てはまらない場合の共通処理
1358             var count = SettingCommon.Instance.CountApi;
1359
1360             if (type == MyCommon.WORKERTYPE.Reply)
1361                 count = SettingCommon.Instance.CountApiReply;
1362
1363             return Math.Min(count, GetMaxApiResultCount(type));
1364         }
1365
1366         public void GetTimelineApi(bool read,
1367                                 MyCommon.WORKERTYPE gType,
1368                                 bool more,
1369                                 bool startup)
1370         {
1371             this.CheckAccountState();
1372
1373             HttpStatusCode res;
1374             var content = "";
1375             var count = GetApiResultCount(gType, more, startup);
1376
1377             try
1378             {
1379                 if (gType == MyCommon.WORKERTYPE.Timeline)
1380                 {
1381                     if (more)
1382                     {
1383                         res = twCon.HomeTimeline(count, this.minHomeTimeline, null, ref content);
1384                     }
1385                     else
1386                     {
1387                         res = twCon.HomeTimeline(count, null, null, ref content);
1388                     }
1389                 }
1390                 else
1391                 {
1392                     if (more)
1393                     {
1394                         res = twCon.Mentions(count, this.minMentions, null, ref content);
1395                     }
1396                     else
1397                     {
1398                         res = twCon.Mentions(count, null, null, ref content);
1399                     }
1400                 }
1401             }
1402             catch(Exception ex)
1403             {
1404                 throw new WebApiException("Err:" + ex.Message, ex);
1405             }
1406
1407             this.CheckStatusCode(res, content);
1408
1409             var minimumId = CreatePostsFromJson(content, gType, null, read);
1410
1411             if (minimumId != null)
1412             {
1413                 if (gType == MyCommon.WORKERTYPE.Timeline)
1414                     this.minHomeTimeline = minimumId.Value;
1415                 else
1416                     this.minMentions = minimumId.Value;
1417             }
1418         }
1419
1420         public void GetUserTimelineApi(bool read,
1421                                          string userName,
1422                                          TabClass tab,
1423                                          bool more)
1424         {
1425             this.CheckAccountState();
1426
1427             HttpStatusCode res;
1428             var content = "";
1429             var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
1430
1431             try
1432             {
1433                 if (string.IsNullOrEmpty(userName))
1434                 {
1435                     var target = tab.User;
1436                     if (string.IsNullOrEmpty(target)) return;
1437                     userName = target;
1438                     res = twCon.UserTimeline(null, target, count, null, null, ref content);
1439                 }
1440                 else
1441                 {
1442                     if (more)
1443                     {
1444                         res = twCon.UserTimeline(null, userName, count, tab.OldestId, null, ref content);
1445                     }
1446                     else
1447                     {
1448                         res = twCon.UserTimeline(null, userName, count, null, null, ref content);
1449                     }
1450                 }
1451             }
1452             catch(Exception ex)
1453             {
1454                 throw new WebApiException("Err:" + ex.Message, ex);
1455             }
1456
1457             if (res == HttpStatusCode.Unauthorized)
1458                 throw new WebApiException("Err:@" + userName + "'s Tweets are protected.");
1459
1460             this.CheckStatusCode(res, content);
1461
1462             var minimumId = CreatePostsFromJson(content, MyCommon.WORKERTYPE.UserTimeline, tab, read);
1463
1464             if (minimumId != null)
1465                 tab.OldestId = minimumId.Value;
1466         }
1467
1468         public PostClass GetStatusApi(bool read, long id)
1469         {
1470             this.CheckAccountState();
1471
1472             HttpStatusCode res;
1473             var content = "";
1474             try
1475             {
1476                 res = twCon.ShowStatuses(id, ref content);
1477             }
1478             catch(Exception ex)
1479             {
1480                 throw new WebApiException("Err:" + ex.Message, ex);
1481             }
1482
1483             if (res == HttpStatusCode.Forbidden)
1484                 throw new WebApiException("Err:protected user's tweet", content);
1485
1486             this.CheckStatusCode(res, content);
1487
1488             TwitterStatus status;
1489             try
1490             {
1491                 status = TwitterStatus.ParseJson(content);
1492             }
1493             catch(SerializationException ex)
1494             {
1495                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1496                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1497             }
1498             catch(Exception ex)
1499             {
1500                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1501                 throw new WebApiException("Invalid Json!", content, ex);
1502             }
1503
1504             var item = CreatePostsFromStatusData(status);
1505             if (item == null)
1506                 throw new WebApiException("Err:Can't create post", content);
1507
1508             item.IsRead = read;
1509             if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
1510
1511             return item;
1512         }
1513
1514         public void GetStatusApi(bool read, long id, TabClass tab)
1515         {
1516             var post = this.GetStatusApi(read, id);
1517
1518             //非同期アイコン取得&StatusDictionaryに追加
1519             if (tab != null && tab.IsInnerStorageTabType)
1520                 tab.AddPostToInnerStorage(post);
1521             else
1522                 TabInformations.GetInstance().AddPost(post);
1523         }
1524
1525         private PostClass CreatePostsFromStatusData(TwitterStatus status)
1526         {
1527             return CreatePostsFromStatusData(status, false);
1528         }
1529
1530         private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
1531         {
1532             var post = new PostClass();
1533             TwitterEntities entities;
1534             string sourceHtml;
1535
1536             post.StatusId = status.Id;
1537             if (status.RetweetedStatus != null)
1538             {
1539                 var retweeted = status.RetweetedStatus;
1540
1541                 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
1542
1543                 //Id
1544                 post.RetweetedId = retweeted.Id;
1545                 //本文
1546                 post.TextFromApi = retweeted.Text;
1547                 entities = retweeted.MergedEntities;
1548                 sourceHtml = retweeted.Source;
1549                 //Reply先
1550                 post.InReplyToStatusId = retweeted.InReplyToStatusId;
1551                 post.InReplyToUser = retweeted.InReplyToScreenName;
1552                 post.InReplyToUserId = status.InReplyToUserId;
1553
1554                 if (favTweet)
1555                 {
1556                     post.IsFav = true;
1557                 }
1558                 else
1559                 {
1560                     //幻覚fav対策
1561                     var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1562                     post.IsFav = tc.Contains(retweeted.Id);
1563                 }
1564
1565                 if (retweeted.Coordinates != null)
1566                     post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
1567
1568                 //以下、ユーザー情報
1569                 var user = retweeted.User;
1570
1571                 if (user == null || user.ScreenName == null || status.User.ScreenName == null) return null;
1572
1573                 post.UserId = user.Id;
1574                 post.ScreenName = user.ScreenName;
1575                 post.Nickname = user.Name.Trim();
1576                 post.ImageUrl = user.ProfileImageUrlHttps;
1577                 post.IsProtect = user.Protected;
1578
1579                 //Retweetした人
1580                 post.RetweetedBy = status.User.ScreenName;
1581                 post.RetweetedByUserId = status.User.Id;
1582                 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
1583             }
1584             else
1585             {
1586                 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
1587                 //本文
1588                 post.TextFromApi = status.Text;
1589                 entities = status.MergedEntities;
1590                 sourceHtml = status.Source;
1591                 post.InReplyToStatusId = status.InReplyToStatusId;
1592                 post.InReplyToUser = status.InReplyToScreenName;
1593                 post.InReplyToUserId = status.InReplyToUserId;
1594
1595                 if (favTweet)
1596                 {
1597                     post.IsFav = true;
1598                 }
1599                 else
1600                 {
1601                     //幻覚fav対策
1602                     var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1603                     post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
1604                 }
1605
1606                 if (status.Coordinates != null)
1607                     post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
1608
1609                 //以下、ユーザー情報
1610                 var user = status.User;
1611
1612                 if (user == null || user.ScreenName == null) return null;
1613
1614                 post.UserId = user.Id;
1615                 post.ScreenName = user.ScreenName;
1616                 post.Nickname = user.Name.Trim();
1617                 post.ImageUrl = user.ProfileImageUrlHttps;
1618                 post.IsProtect = user.Protected;
1619                 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
1620             }
1621             //HTMLに整形
1622             string textFromApi = post.TextFromApi;
1623             post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
1624             post.TextFromApi = textFromApi;
1625             post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
1626             post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1627             post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1628
1629             post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
1630                 .Where(x => x != post.StatusId && x != post.RetweetedId)
1631                 .Distinct().ToArray();
1632
1633             post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
1634                 .Where(x => x != null)
1635                 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1636                 .ToArray();
1637
1638             //Source整形
1639             var source = ParseSource(sourceHtml);
1640             post.Source = source.Item1;
1641             post.SourceUri = source.Item2;
1642
1643             post.IsReply = post.ReplyToList.Contains(_uname);
1644             post.IsExcludeReply = false;
1645
1646             if (post.IsMe)
1647             {
1648                 post.IsOwl = false;
1649             }
1650             else
1651             {
1652                 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
1653             }
1654
1655             post.IsDm = false;
1656             return post;
1657         }
1658
1659         /// <summary>
1660         /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
1661         /// </summary>
1662         public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
1663         {
1664             var urls = entities.OfType<TwitterEntityUrl>().Where(x => x != null)
1665                 .Select(x => x.ExpandedUrl);
1666
1667             return GetQuoteTweetStatusIds(urls);
1668         }
1669
1670         public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
1671         {
1672             foreach (var url in urls)
1673             {
1674                 var match = Twitter.StatusUrlRegex.Match(url);
1675                 if (match.Success)
1676                 {
1677                     long statusId;
1678                     if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
1679                         yield return statusId;
1680                 }
1681             }
1682         }
1683
1684         private long? CreatePostsFromJson(string content, MyCommon.WORKERTYPE gType, TabClass tab, bool read)
1685         {
1686             TwitterStatus[] items;
1687             try
1688             {
1689                 items = TwitterStatus.ParseJsonArray(content);
1690             }
1691             catch(SerializationException ex)
1692             {
1693                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1694                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1695             }
1696             catch(Exception ex)
1697             {
1698                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1699                 throw new WebApiException("Invalid Json!", content, ex);
1700             }
1701
1702             long? minimumId = null;
1703
1704             foreach (var status in items)
1705             {
1706                 PostClass post = null;
1707                 post = CreatePostsFromStatusData(status);
1708                 if (post == null) continue;
1709
1710                 if (minimumId == null || minimumId.Value > post.StatusId)
1711                     minimumId = post.StatusId;
1712
1713                 //二重取得回避
1714                 lock (LockObj)
1715                 {
1716                     if (tab == null)
1717                     {
1718                         if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1719                     }
1720                     else
1721                     {
1722                         if (tab.Contains(post.StatusId)) continue;
1723                     }
1724                 }
1725
1726                 //RT禁止ユーザーによるもの
1727                 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
1728                     post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
1729
1730                 post.IsRead = read;
1731                 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1732
1733                 //非同期アイコン取得&StatusDictionaryに追加
1734                 if (tab != null && tab.IsInnerStorageTabType)
1735                     tab.AddPostToInnerStorage(post);
1736                 else
1737                     TabInformations.GetInstance().AddPost(post);
1738             }
1739
1740             return minimumId;
1741         }
1742
1743         private long? CreatePostsFromSearchJson(string content, TabClass tab, bool read, int count, bool more)
1744         {
1745             TwitterSearchResult items;
1746             try
1747             {
1748                 items = TwitterSearchResult.ParseJson(content);
1749             }
1750             catch (SerializationException ex)
1751             {
1752                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1753                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1754             }
1755             catch (Exception ex)
1756             {
1757                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1758                 throw new WebApiException("Invalid Json!", content, ex);
1759             }
1760
1761             long? minimumId = null;
1762
1763             foreach (var result in items.Statuses)
1764             {
1765                 PostClass post = null;
1766                 post = CreatePostsFromStatusData(result);
1767
1768                 if (post == null)
1769                 {
1770                     // Search API は相変わらずぶっ壊れたデータを返すことがあるため、必要なデータが欠如しているものは取得し直す
1771                     try
1772                     {
1773                         post = this.GetStatusApi(read, result.Id);
1774                     }
1775                     catch (WebApiException)
1776                     {
1777                         continue;
1778                     }
1779                 }
1780
1781                 if (minimumId == null || minimumId.Value > post.StatusId)
1782                     minimumId = post.StatusId;
1783
1784                 if (!more && post.StatusId > tab.SinceId) tab.SinceId = post.StatusId;
1785                 //二重取得回避
1786                 lock (LockObj)
1787                 {
1788                     if (tab == null)
1789                     {
1790                         if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1791                     }
1792                     else
1793                     {
1794                         if (tab.Contains(post.StatusId)) continue;
1795                     }
1796                 }
1797
1798                 post.IsRead = read;
1799                 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
1800
1801                 //非同期アイコン取得&StatusDictionaryに追加
1802                 if (tab != null && tab.IsInnerStorageTabType)
1803                     tab.AddPostToInnerStorage(post);
1804                 else
1805                     TabInformations.GetInstance().AddPost(post);
1806             }
1807
1808             return minimumId;
1809         }
1810
1811         private void CreateFavoritePostsFromJson(string content, bool read)
1812         {
1813             TwitterStatus[] item;
1814             try
1815             {
1816                 item = TwitterStatus.ParseJsonArray(content);
1817             }
1818             catch (SerializationException ex)
1819             {
1820                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1821                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1822             }
1823             catch (Exception ex)
1824             {
1825                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1826                 throw new WebApiException("Invalid Json!", content, ex);
1827             }
1828
1829             var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1830
1831             foreach (var status in item)
1832             {
1833                 //二重取得回避
1834                 lock (LockObj)
1835                 {
1836                     if (favTab.Contains(status.Id)) continue;
1837                 }
1838
1839                 var post = CreatePostsFromStatusData(status, true);
1840                 if (post == null) continue;
1841
1842                 post.IsRead = read;
1843
1844                 TabInformations.GetInstance().AddPost(post);
1845             }
1846         }
1847
1848         public void GetListStatus(bool read,
1849                                 TabClass tab,
1850                                 bool more,
1851                                 bool startup)
1852         {
1853             HttpStatusCode res;
1854             var content = "";
1855             var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
1856
1857             try
1858             {
1859                 if (more)
1860                 {
1861                     res = twCon.GetListsStatuses(tab.ListInfo.UserId, tab.ListInfo.Id, count, tab.OldestId, null, SettingCommon.Instance.IsListsIncludeRts, ref content);
1862                 }
1863                 else
1864                 {
1865                     res = twCon.GetListsStatuses(tab.ListInfo.UserId, tab.ListInfo.Id, count, null, null, SettingCommon.Instance.IsListsIncludeRts, ref content);
1866                 }
1867             }
1868             catch(Exception ex)
1869             {
1870                 throw new WebApiException("Err:" + ex.Message, ex);
1871             }
1872
1873             this.CheckStatusCode(res, content);
1874
1875             var minimumId = CreatePostsFromJson(content, MyCommon.WORKERTYPE.List, tab, read);
1876
1877             if (minimumId != null)
1878                 tab.OldestId = minimumId.Value;
1879         }
1880
1881         /// <summary>
1882         /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1883         /// </summary>
1884         /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1885         internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1886         {
1887             if (!posts.ContainsKey(startStatusId))
1888                 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1889
1890             var nextPost = posts[startStatusId];
1891             while (nextPost.InReplyToStatusId != null)
1892             {
1893                 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1894                     break;
1895                 nextPost = posts[nextPost.InReplyToStatusId.Value];
1896             }
1897
1898             return nextPost;
1899         }
1900
1901         public void GetRelatedResult(bool read, TabClass tab)
1902         {
1903             var relPosts = new Dictionary<Int64, PostClass>();
1904             if (tab.RelationTargetPost.TextFromApi.Contains("@") && tab.RelationTargetPost.InReplyToStatusId == null)
1905             {
1906                 //検索結果対応
1907                 var p = TabInformations.GetInstance()[tab.RelationTargetPost.StatusId];
1908                 if (p != null && p.InReplyToStatusId != null)
1909                 {
1910                     tab.RelationTargetPost = p;
1911                 }
1912                 else
1913                 {
1914                     p = this.GetStatusApi(read, tab.RelationTargetPost.StatusId);
1915                     tab.RelationTargetPost = p;
1916                 }
1917             }
1918             relPosts.Add(tab.RelationTargetPost.StatusId, tab.RelationTargetPost);
1919
1920             Exception lastException = null;
1921
1922             // in_reply_to_status_id を使用してリプライチェインを辿る
1923             var nextPost = FindTopOfReplyChain(relPosts, tab.RelationTargetPost.StatusId);
1924             var loopCount = 1;
1925             while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1926             {
1927                 var inReplyToId = nextPost.InReplyToStatusId.Value;
1928
1929                 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1930                 if (inReplyToPost == null)
1931                 {
1932                     try
1933                     {
1934                         inReplyToPost = this.GetStatusApi(read, inReplyToId);
1935                     }
1936                     catch (WebApiException ex)
1937                     {
1938                         lastException = ex;
1939                         break;
1940                     }
1941                 }
1942
1943                 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1944
1945                 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1946             }
1947
1948             //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1949             var text = tab.RelationTargetPost.Text;
1950             var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1951                 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1952             foreach (var _match in ma)
1953             {
1954                 Int64 _statusId;
1955                 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1956                 {
1957                     if (relPosts.ContainsKey(_statusId))
1958                         continue;
1959
1960                     var p = TabInformations.GetInstance()[_statusId];
1961                     if (p == null)
1962                     {
1963                         try
1964                         {
1965                             p = this.GetStatusApi(read, _statusId);
1966                         }
1967                         catch (WebApiException ex)
1968                         {
1969                             lastException = ex;
1970                             break;
1971                         }
1972                     }
1973
1974                     if (p != null)
1975                         relPosts.Add(p.StatusId, p);
1976                 }
1977             }
1978
1979             relPosts.Values.ToList().ForEach(p =>
1980             {
1981                 if (p.IsMe && !read && this._readOwnPost)
1982                     p.IsRead = true;
1983                 else
1984                     p.IsRead = read;
1985
1986                 tab.AddPostToInnerStorage(p);
1987             });
1988
1989             if (lastException != null)
1990                 throw new WebApiException(lastException.Message, lastException);
1991         }
1992
1993         public void GetSearch(bool read,
1994                             TabClass tab,
1995                             bool more)
1996         {
1997             HttpStatusCode res;
1998             var content = "";
1999             var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
2000             long? maxId = null;
2001             long? sinceId = null;
2002             if (more)
2003             {
2004                 maxId = tab.OldestId - 1;
2005             }
2006             else
2007             {
2008                 sinceId = tab.SinceId;
2009             }
2010
2011             try
2012             {
2013                 // TODO:一時的に40>100件に 件数変更UI作成の必要あり
2014                 res = twCon.Search(tab.SearchWords, tab.SearchLang, count, maxId, sinceId, ref content);
2015             }
2016             catch(Exception ex)
2017             {
2018                 throw new WebApiException("Err:" + ex.Message, ex);
2019             }
2020             switch (res)
2021             {
2022                 case HttpStatusCode.BadRequest:
2023                     throw new WebApiException("Invalid query", content);
2024                 case HttpStatusCode.NotFound:
2025                     throw new WebApiException("Invalid query", content);
2026                 case HttpStatusCode.PaymentRequired: //API Documentには420と書いてあるが、該当コードがないので402にしてある
2027                     throw new WebApiException("Search API Limit?", content);
2028                 case HttpStatusCode.OK:
2029                     break;
2030                 default:
2031                     throw new WebApiException("Err:" + res.ToString() + "(" + MethodBase.GetCurrentMethod().Name + ")", content);
2032             }
2033
2034             if (!TabInformations.GetInstance().ContainsTab(tab))
2035                 return;
2036
2037             var minimumId =  this.CreatePostsFromSearchJson(content, tab, read, count, more);
2038
2039             if (minimumId != null)
2040                 tab.OldestId = minimumId.Value;
2041         }
2042
2043         private void CreateDirectMessagesFromJson(string content, MyCommon.WORKERTYPE gType, bool read)
2044         {
2045             TwitterDirectMessage[] item;
2046             try
2047             {
2048                 if (gType == MyCommon.WORKERTYPE.UserStream)
2049                 {
2050                     item = new[] { TwitterStreamEventDirectMessage.ParseJson(content).DirectMessage };
2051                 }
2052                 else
2053                 {
2054                     item = TwitterDirectMessage.ParseJsonArray(content);
2055                 }
2056             }
2057             catch(SerializationException ex)
2058             {
2059                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2060                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
2061             }
2062             catch(Exception ex)
2063             {
2064                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2065                 throw new WebApiException("Invalid Json!", content, ex);
2066             }
2067
2068             foreach (var message in item)
2069             {
2070                 var post = new PostClass();
2071                 try
2072                 {
2073                     post.StatusId = message.Id;
2074                     if (gType != MyCommon.WORKERTYPE.UserStream)
2075                     {
2076                         if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
2077                         {
2078                             if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
2079                         }
2080                         else
2081                         {
2082                             if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
2083                         }
2084                     }
2085
2086                     //二重取得回避
2087                     lock (LockObj)
2088                     {
2089                         if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
2090                     }
2091                     //sender_id
2092                     //recipient_id
2093                     post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
2094                     //本文
2095                     var textFromApi = message.Text;
2096                     //HTMLに整形
2097                     post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
2098                     post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
2099                     post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
2100                     post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
2101                     post.IsFav = false;
2102
2103                     post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
2104
2105                     post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
2106                         .Where(x => x != null)
2107                         .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
2108                         .ToArray();
2109
2110                     //以下、ユーザー情報
2111                     TwitterUser user;
2112                     if (gType == MyCommon.WORKERTYPE.UserStream)
2113                     {
2114                         if (twCon.AuthenticatedUsername.Equals(message.Recipient.ScreenName, StringComparison.CurrentCultureIgnoreCase))
2115                         {
2116                             user = message.Sender;
2117                             post.IsMe = false;
2118                             post.IsOwl = true;
2119                         }
2120                         else
2121                         {
2122                             user = message.Recipient;
2123                             post.IsMe = true;
2124                             post.IsOwl = false;
2125                         }
2126                     }
2127                     else
2128                     {
2129                         if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
2130                         {
2131                             user = message.Sender;
2132                             post.IsMe = false;
2133                             post.IsOwl = true;
2134                         }
2135                         else
2136                         {
2137                             user = message.Recipient;
2138                             post.IsMe = true;
2139                             post.IsOwl = false;
2140                         }
2141                     }
2142
2143                     post.UserId = user.Id;
2144                     post.ScreenName = user.ScreenName;
2145                     post.Nickname = user.Name.Trim();
2146                     post.ImageUrl = user.ProfileImageUrlHttps;
2147                     post.IsProtect = user.Protected;
2148                 }
2149                 catch(Exception ex)
2150                 {
2151                     MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2152                     MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
2153                     continue;
2154                 }
2155
2156                 post.IsRead = read;
2157                 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
2158                 post.IsReply = false;
2159                 post.IsExcludeReply = false;
2160                 post.IsDm = true;
2161
2162                 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
2163                 dmTab.AddPostToInnerStorage(post);
2164             }
2165         }
2166
2167         public void GetDirectMessageApi(bool read,
2168                                 MyCommon.WORKERTYPE gType,
2169                                 bool more)
2170         {
2171             this.CheckAccountState();
2172             this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
2173
2174             HttpStatusCode res;
2175             var content = "";
2176             var count = GetApiResultCount(gType, more, false);
2177
2178             try
2179             {
2180                 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
2181                 {
2182                     if (more)
2183                     {
2184                         res = twCon.DirectMessages(count, minDirectmessage, null, ref content);
2185                     }
2186                     else
2187                     {
2188                         res = twCon.DirectMessages(count, null, null, ref content);
2189                     }
2190                 }
2191                 else
2192                 {
2193                     if (more)
2194                     {
2195                         res = twCon.DirectMessagesSent(count, minDirectmessageSent, null, ref content);
2196                     }
2197                     else
2198                     {
2199                         res = twCon.DirectMessagesSent(count, null, null, ref content);
2200                     }
2201                 }
2202             }
2203             catch(Exception ex)
2204             {
2205                 throw new WebApiException("Err:" + ex.Message, ex);
2206             }
2207
2208             this.CheckStatusCode(res, content);
2209
2210             CreateDirectMessagesFromJson(content, gType, read);
2211         }
2212
2213         public void GetFavoritesApi(bool read,
2214                             bool more)
2215         {
2216             this.CheckAccountState();
2217
2218             HttpStatusCode res;
2219             var content = "";
2220             var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
2221
2222             try
2223             {
2224                 res = twCon.Favorites(count, ref content);
2225             }
2226             catch(Exception ex)
2227             {
2228                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2229             }
2230
2231             this.CheckStatusCode(res, content);
2232
2233             CreateFavoritePostsFromJson(content, read);
2234         }
2235
2236         private string ReplaceTextFromApi(string text, TwitterEntities entities)
2237         {
2238             if (entities != null)
2239             {
2240                 if (entities.Urls != null)
2241                 {
2242                     foreach (var m in entities.Urls)
2243                     {
2244                         if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
2245                     }
2246                 }
2247                 if (entities.Media != null)
2248                 {
2249                     foreach (var m in entities.Media)
2250                     {
2251                         if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
2252                     }
2253                 }
2254             }
2255             return text;
2256         }
2257
2258         /// <summary>
2259         /// フォロワーIDを更新します
2260         /// </summary>
2261         /// <exception cref="WebApiException"/>
2262         public void RefreshFollowerIds()
2263         {
2264             if (MyCommon._endingFlag) return;
2265
2266             var cursor = -1L;
2267             var newFollowerIds = new HashSet<long>();
2268             do
2269             {
2270                 var ret = this.GetFollowerIdsApi(ref cursor);
2271                 newFollowerIds.UnionWith(ret.Ids);
2272                 cursor = ret.NextCursor;
2273             } while (cursor != 0);
2274
2275             this.followerId = newFollowerIds;
2276             TabInformations.GetInstance().RefreshOwl(this.followerId);
2277
2278             this._GetFollowerResult = true;
2279         }
2280
2281         public bool GetFollowersSuccess
2282         {
2283             get
2284             {
2285                 return _GetFollowerResult;
2286             }
2287         }
2288
2289         private TwitterIds GetFollowerIdsApi(ref long cursor)
2290         {
2291             this.CheckAccountState();
2292
2293             HttpStatusCode res;
2294             var content = "";
2295             try
2296             {
2297                 res = twCon.FollowerIds(cursor, ref content);
2298             }
2299             catch(Exception e)
2300             {
2301                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2302             }
2303
2304             this.CheckStatusCode(res, content);
2305
2306             try
2307             {
2308                 var ret = TwitterIds.ParseJson(content);
2309
2310                 if (ret.Ids == null)
2311                 {
2312                     var ex = new WebApiException("Err: ret.id == null (GetFollowerIdsApi)", content);
2313                     MyCommon.ExceptionOut(ex);
2314                     throw ex;
2315                 }
2316
2317                 return ret;
2318             }
2319             catch(SerializationException e)
2320             {
2321                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2322                 MyCommon.TraceOut(ex);
2323                 throw ex;
2324             }
2325             catch(Exception e)
2326             {
2327                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2328                 MyCommon.TraceOut(ex);
2329                 throw ex;
2330             }
2331         }
2332
2333         /// <summary>
2334         /// RT 非表示ユーザーを更新します
2335         /// </summary>
2336         /// <exception cref="WebApiException"/>
2337         public void RefreshNoRetweetIds()
2338         {
2339             if (MyCommon._endingFlag) return;
2340
2341             this.noRTId = this.NoRetweetIdsApi();
2342
2343             this._GetNoRetweetResult = true;
2344         }
2345
2346         private long[] NoRetweetIdsApi()
2347         {
2348             this.CheckAccountState();
2349
2350             HttpStatusCode res;
2351             var content = "";
2352             try
2353             {
2354                 res = twCon.NoRetweetIds(ref content);
2355             }
2356             catch(Exception e)
2357             {
2358                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2359             }
2360
2361             this.CheckStatusCode(res, content);
2362
2363             try
2364             {
2365                 return MyCommon.CreateDataFromJson<long[]>(content);
2366             }
2367             catch(SerializationException e)
2368             {
2369                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2370                 MyCommon.TraceOut(ex);
2371                 throw ex;
2372             }
2373             catch(Exception e)
2374             {
2375                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2376                 MyCommon.TraceOut(ex);
2377                 throw ex;
2378             }
2379         }
2380
2381         public bool GetNoRetweetSuccess
2382         {
2383             get
2384             {
2385                 return _GetNoRetweetResult;
2386             }
2387         }
2388
2389         /// <summary>
2390         /// t.co の文字列長などの設定情報を更新します
2391         /// </summary>
2392         /// <exception cref="WebApiException"/>
2393         public void RefreshConfiguration()
2394         {
2395             this.Configuration = this.ConfigurationApi();
2396         }
2397
2398         private TwitterConfiguration ConfigurationApi()
2399         {
2400             HttpStatusCode res;
2401             var content = "";
2402             try
2403             {
2404                 res = twCon.GetConfiguration(ref content);
2405             }
2406             catch(Exception e)
2407             {
2408                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2409             }
2410
2411             this.CheckStatusCode(res, content);
2412
2413             try
2414             {
2415                 return TwitterConfiguration.ParseJson(content);
2416             }
2417             catch(SerializationException e)
2418             {
2419                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2420                 MyCommon.TraceOut(ex);
2421                 throw ex;
2422             }
2423             catch(Exception e)
2424             {
2425                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2426                 MyCommon.TraceOut(ex);
2427                 throw ex;
2428             }
2429         }
2430
2431         public void GetListsApi()
2432         {
2433             this.CheckAccountState();
2434
2435             HttpStatusCode res;
2436             IEnumerable<ListElement> lists;
2437             var content = "";
2438
2439             try
2440             {
2441                 res = twCon.GetLists(this.Username, ref content);
2442             }
2443             catch (Exception ex)
2444             {
2445                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2446             }
2447
2448             this.CheckStatusCode(res, content);
2449
2450             try
2451             {
2452                 lists = TwitterList.ParseJsonArray(content)
2453                     .Select(x => new ListElement(x, this));
2454             }
2455             catch (SerializationException ex)
2456             {
2457                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2458                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2459             }
2460             catch (Exception ex)
2461             {
2462                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2463                 throw new WebApiException("Err:Invalid Json!", content, ex);
2464             }
2465
2466             try
2467             {
2468                 res = twCon.GetListsSubscriptions(this.Username, ref content);
2469             }
2470             catch (Exception ex)
2471             {
2472                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2473             }
2474
2475             this.CheckStatusCode(res, content);
2476
2477             try
2478             {
2479                 lists = lists.Concat(TwitterList.ParseJsonArray(content)
2480                     .Select(x => new ListElement(x, this)));
2481             }
2482             catch (SerializationException ex)
2483             {
2484                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2485                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2486             }
2487             catch (Exception ex)
2488             {
2489                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2490                 throw new WebApiException("Err:Invalid Json!", content, ex);
2491             }
2492
2493             TabInformations.GetInstance().SubscribableLists = lists.ToList();
2494         }
2495
2496         public void DeleteList(string list_id)
2497         {
2498             HttpStatusCode res;
2499             var content = "";
2500
2501             try
2502             {
2503                 res = twCon.DeleteListID(this.Username, list_id, ref content);
2504             }
2505             catch(Exception ex)
2506             {
2507                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2508             }
2509
2510             this.CheckStatusCode(res, content);
2511         }
2512
2513         public ListElement EditList(string list_id, string new_name, bool isPrivate, string description)
2514         {
2515             HttpStatusCode res;
2516             var content = "";
2517
2518             try
2519             {
2520                 res = twCon.UpdateListID(this.Username, list_id, new_name, isPrivate, description, ref content);
2521             }
2522             catch(Exception ex)
2523             {
2524                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2525             }
2526
2527             this.CheckStatusCode(res, content);
2528
2529             try
2530             {
2531                 var le = TwitterList.ParseJson(content);
2532                 return  new ListElement(le, this);
2533             }
2534             catch(SerializationException ex)
2535             {
2536                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2537                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2538             }
2539             catch(Exception ex)
2540             {
2541                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2542                 throw new WebApiException("Err:Invalid Json!", content, ex);
2543             }
2544         }
2545
2546         public long GetListMembers(string list_id, List<UserInfo> lists, long cursor)
2547         {
2548             this.CheckAccountState();
2549
2550             HttpStatusCode res;
2551             var content = "";
2552             try
2553             {
2554                 res = twCon.GetListMembers(this.Username, list_id, cursor, ref content);
2555             }
2556             catch(Exception ex)
2557             {
2558                 throw new WebApiException("Err:" + ex.Message);
2559             }
2560
2561             this.CheckStatusCode(res, content);
2562
2563             try
2564             {
2565                 var users = TwitterUsers.ParseJson(content);
2566                 Array.ForEach<TwitterUser>(
2567                     users.Users,
2568                     u => lists.Add(new UserInfo(u)));
2569
2570                 return users.NextCursor;
2571             }
2572             catch(SerializationException ex)
2573             {
2574                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2575                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2576             }
2577             catch(Exception ex)
2578             {
2579                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2580                 throw new WebApiException("Err:Invalid Json!", content, ex);
2581             }
2582         }
2583
2584         public void CreateListApi(string listName, bool isPrivate, string description)
2585         {
2586             this.CheckAccountState();
2587
2588             HttpStatusCode res;
2589             var content = "";
2590             try
2591             {
2592                 res = twCon.CreateLists(listName, isPrivate, description, ref content);
2593             }
2594             catch(Exception ex)
2595             {
2596                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2597             }
2598
2599             this.CheckStatusCode(res, content);
2600
2601             try
2602             {
2603                 var le = TwitterList.ParseJson(content);
2604                 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(le, this));
2605             }
2606             catch(SerializationException ex)
2607             {
2608                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2609                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2610             }
2611             catch(Exception ex)
2612             {
2613                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2614                 throw new WebApiException("Err:Invalid Json!", content, ex);
2615             }
2616         }
2617
2618         public bool ContainsUserAtList(string listId, string user)
2619         {
2620             this.CheckAccountState();
2621
2622             HttpStatusCode res;
2623             var content = "";
2624
2625             try
2626             {
2627                 res = this.twCon.ShowListMember(listId, user, ref content);
2628             }
2629             catch(Exception ex)
2630             {
2631                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2632             }
2633
2634             if (res == HttpStatusCode.NotFound)
2635             {
2636                 return false;
2637             }
2638
2639             this.CheckStatusCode(res, content);
2640
2641             try
2642             {
2643                 TwitterUser.ParseJson(content);
2644                 return true;
2645             }
2646             catch(Exception)
2647             {
2648                 return false;
2649             }
2650         }
2651
2652         public void AddUserToList(string listId, string user)
2653         {
2654             HttpStatusCode res;
2655             var content = "";
2656
2657             try
2658             {
2659                 res = twCon.CreateListMembers(listId, user, ref content);
2660             }
2661             catch(Exception ex)
2662             {
2663                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2664             }
2665
2666             this.CheckStatusCode(res, content);
2667         }
2668
2669         public void RemoveUserToList(string listId, string user)
2670         {
2671             HttpStatusCode res;
2672             var content = "";
2673
2674             try
2675             {
2676                 res = twCon.DeleteListMembers(listId, user, ref content);
2677             }
2678             catch(Exception ex)
2679             {
2680                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2681             }
2682
2683             this.CheckStatusCode(res, content);
2684         }
2685
2686         public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
2687         {
2688             if (entities != null)
2689             {
2690                 if (entities.Hashtags != null)
2691                 {
2692                     lock (this.LockObj)
2693                     {
2694                         this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
2695                     }
2696                 }
2697                 if (entities.UserMentions != null)
2698                 {
2699                     foreach (var ent in entities.UserMentions)
2700                     {
2701                         var screenName = ent.ScreenName.ToLowerInvariant();
2702                         if (!AtList.Contains(screenName))
2703                             AtList.Add(screenName);
2704                     }
2705                 }
2706                 if (entities.Media != null)
2707                 {
2708                     if (media != null)
2709                     {
2710                         foreach (var ent in entities.Media)
2711                         {
2712                             if (!media.Any(x => x.Url == ent.MediaUrl))
2713                             {
2714                                 if (ent.VideoInfo != null &&
2715                                     ent.Type == "animated_gif" || ent.Type == "video")
2716                                 {
2717                                     //var videoUrl = ent.VideoInfo.Variants
2718                                     //    .Where(v => v.ContentType == "video/mp4")
2719                                     //    .OrderByDescending(v => v.Bitrate)
2720                                     //    .Select(v => v.Url).FirstOrDefault();
2721                                     media.Add(new MediaInfo(ent.MediaUrl, ent.ExpandedUrl));
2722                                 }
2723                                 else
2724                                     media.Add(new MediaInfo(ent.MediaUrl));
2725                             }
2726                         }
2727                     }
2728                 }
2729             }
2730
2731             // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
2732             text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
2733
2734             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>");
2735             text = PreProcessUrl(text); //IDN置換
2736
2737             return text;
2738         }
2739
2740         private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
2741
2742         /// <summary>
2743         /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
2744         /// </summary>
2745         public static Tuple<string, Uri> ParseSource(string sourceHtml)
2746         {
2747             if (string.IsNullOrEmpty(sourceHtml))
2748                 return Tuple.Create<string, Uri>("", null);
2749
2750             string sourceText;
2751             Uri sourceUri;
2752
2753             // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
2754
2755             var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
2756             if (match.Success)
2757             {
2758                 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
2759                 try
2760                 {
2761                     var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
2762                     sourceUri = new Uri(SourceUriBase, uriStr);
2763                 }
2764                 catch (UriFormatException)
2765                 {
2766                     sourceUri = null;
2767                 }
2768             }
2769             else
2770             {
2771                 sourceText = WebUtility.HtmlDecode(sourceHtml);
2772                 sourceUri = null;
2773             }
2774
2775             return Tuple.Create(sourceText, sourceUri);
2776         }
2777
2778         public TwitterApiStatus GetInfoApi()
2779         {
2780             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
2781
2782             if (MyCommon._endingFlag) return null;
2783
2784             HttpStatusCode res;
2785             var content = "";
2786             try
2787             {
2788                 res = twCon.RateLimitStatus(ref content);
2789             }
2790             catch (Exception)
2791             {
2792                 this.ResetApiStatus();
2793                 return null;
2794             }
2795
2796             this.CheckStatusCode(res, content);
2797
2798             try
2799             {
2800                 MyCommon.TwitterApiInfo.UpdateFromJson(content);
2801                 return MyCommon.TwitterApiInfo;
2802             }
2803             catch (Exception ex)
2804             {
2805                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2806                 MyCommon.TwitterApiInfo.Reset();
2807                 return null;
2808             }
2809         }
2810
2811         /// <summary>
2812         /// ブロック中のユーザーを更新します
2813         /// </summary>
2814         /// <exception cref="WebApiException"/>
2815         public void RefreshBlockIds()
2816         {
2817             if (MyCommon._endingFlag) return;
2818
2819             var cursor = -1L;
2820             var newBlockIds = new HashSet<long>();
2821             do
2822             {
2823                 var ret = this.GetBlockIdsApi(cursor);
2824                 newBlockIds.UnionWith(ret.Ids);
2825                 cursor = ret.NextCursor;
2826             } while (cursor != 0);
2827
2828             newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
2829
2830             TabInformations.GetInstance().BlockIds = newBlockIds;
2831         }
2832
2833         public TwitterIds GetBlockIdsApi(long cursor)
2834         {
2835             this.CheckAccountState();
2836
2837             HttpStatusCode res;
2838             var content = "";
2839             try
2840             {
2841                 res = twCon.GetBlockUserIds(ref content, cursor);
2842             }
2843             catch(Exception e)
2844             {
2845                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2846             }
2847
2848             this.CheckStatusCode(res, content);
2849
2850             try
2851             {
2852                 return TwitterIds.ParseJson(content);
2853             }
2854             catch(SerializationException e)
2855             {
2856                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2857                 MyCommon.TraceOut(ex);
2858                 throw ex;
2859             }
2860             catch(Exception e)
2861             {
2862                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2863                 MyCommon.TraceOut(ex);
2864                 throw ex;
2865             }
2866         }
2867
2868         /// <summary>
2869         /// ミュート中のユーザーIDを更新します
2870         /// </summary>
2871         /// <exception cref="WebApiException"/>
2872         public async Task RefreshMuteUserIdsAsync()
2873         {
2874             if (MyCommon._endingFlag) return;
2875
2876             var ids = await TwitterIds.GetAllItemsAsync(this.GetMuteUserIdsApiAsync)
2877                 .ConfigureAwait(false);
2878
2879             TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
2880         }
2881
2882         public async Task<TwitterIds> GetMuteUserIdsApiAsync(long cursor)
2883         {
2884             var content = "";
2885
2886             try
2887             {
2888                 var res = await Task.Run(() => twCon.GetMuteUserIds(ref content, cursor))
2889                     .ConfigureAwait(false);
2890
2891                 this.CheckStatusCode(res, content);
2892
2893                 return TwitterIds.ParseJson(content);
2894             }
2895             catch (WebException ex)
2896             {
2897                 var ex2 = new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", content, ex);
2898                 MyCommon.TraceOut(ex2);
2899                 throw ex2;
2900             }
2901             catch (SerializationException ex)
2902             {
2903                 var ex2 = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2904                 MyCommon.TraceOut(ex2);
2905                 throw ex2;
2906             }
2907         }
2908
2909         public string[] GetHashList()
2910         {
2911             string[] hashArray;
2912             lock (LockObj)
2913             {
2914                 hashArray = _hashList.ToArray();
2915                 _hashList.Clear();
2916             }
2917             return hashArray;
2918         }
2919
2920         public string AccessToken
2921         {
2922             get
2923             {
2924                 return twCon.AccessToken;
2925             }
2926         }
2927
2928         public string AccessTokenSecret
2929         {
2930             get
2931             {
2932                 return twCon.AccessTokenSecret;
2933             }
2934         }
2935
2936         private void CheckAccountState()
2937         {
2938             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2939                 throw new WebApiException("Auth error. Check your account");
2940         }
2941
2942         private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
2943         {
2944             if (!this.AccessLevel.HasFlag(accessLevelFlags))
2945                 throw new WebApiException("Auth Err:try to re-authorization.");
2946         }
2947
2948         private void CheckStatusCode(HttpStatusCode httpStatus, string responseText,
2949             [CallerMemberName] string callerMethodName = "")
2950         {
2951             if (httpStatus == HttpStatusCode.OK)
2952             {
2953                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2954                 return;
2955             }
2956
2957             if (string.IsNullOrWhiteSpace(responseText))
2958             {
2959                 if (httpStatus == HttpStatusCode.Unauthorized)
2960                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2961
2962                 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")");
2963             }
2964
2965             try
2966             {
2967                 var errors = TwitterError.ParseJson(responseText).Errors;
2968                 if (errors == null || !errors.Any())
2969                 {
2970                     throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2971                 }
2972
2973                 foreach (var error in errors)
2974                 {
2975                     if (error.Code == TwitterErrorCode.InvalidToken ||
2976                         error.Code == TwitterErrorCode.SuspendedAccount)
2977                     {
2978                         Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2979                     }
2980                 }
2981
2982                 throw new WebApiException("Err:" + string.Join(",", errors.Select(x => x.ToString())) + "(" + callerMethodName + ")", responseText);
2983             }
2984             catch (SerializationException) { }
2985
2986             throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2987         }
2988
2989         public int GetTextLengthRemain(string postText)
2990         {
2991             var matchDm = Twitter.DMSendTextRegex.Match(postText);
2992             if (matchDm.Success)
2993                 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
2994
2995             return this.GetTextLengthRemainInternal(postText, isDm: false);
2996         }
2997
2998         private int GetTextLengthRemainInternal(string postText, bool isDm)
2999         {
3000             var textLength = 0;
3001
3002             var pos = 0;
3003             while (pos < postText.Length)
3004             {
3005                 textLength++;
3006
3007                 if (char.IsSurrogatePair(postText, pos))
3008                     pos += 2; // サロゲートペアの場合は2文字分進める
3009                 else
3010                     pos++;
3011             }
3012
3013             var urls = TweetExtractor.ExtractUrls(postText);
3014             foreach (var url in urls)
3015             {
3016                 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
3017                     ? this.Configuration.ShortUrlLengthHttps
3018                     : this.Configuration.ShortUrlLength;
3019
3020                 textLength += shortUrlLength - url.Length;
3021             }
3022
3023             if (isDm)
3024                 return this.Configuration.DmTextCharacterLimit - textLength;
3025             else
3026                 return 140 - textLength;
3027         }
3028
3029
3030 #region "UserStream"
3031         private string trackWord_ = "";
3032         public string TrackWord
3033         {
3034             get
3035             {
3036                 return trackWord_;
3037             }
3038             set
3039             {
3040                 trackWord_ = value;
3041             }
3042         }
3043         private bool allAtReply_ = false;
3044         public bool AllAtReply
3045         {
3046             get
3047             {
3048                 return allAtReply_;
3049             }
3050             set
3051             {
3052                 allAtReply_ = value;
3053             }
3054         }
3055
3056         public event EventHandler NewPostFromStream;
3057         public event EventHandler UserStreamStarted;
3058         public event EventHandler UserStreamStopped;
3059         public event EventHandler<PostDeletedEventArgs> PostDeleted;
3060         public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
3061         private DateTime _lastUserstreamDataReceived;
3062         private TwitterUserstream userStream;
3063
3064         public class FormattedEvent
3065         {
3066             public MyCommon.EVENTTYPE Eventtype { get; set; }
3067             public DateTime CreatedAt { get; set; }
3068             public string Event { get; set; }
3069             public string Username { get; set; }
3070             public string Target { get; set; }
3071             public Int64 Id { get; set; }
3072             public bool IsMe { get; set; }
3073         }
3074
3075         public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
3076         public List<FormattedEvent> StoredEvent
3077         {
3078             get
3079             {
3080                 return storedEvent_;
3081             }
3082             set
3083             {
3084                 storedEvent_ = value;
3085             }
3086         }
3087
3088         private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
3089         {
3090             ["favorite"] = MyCommon.EVENTTYPE.Favorite,
3091             ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
3092             ["follow"] = MyCommon.EVENTTYPE.Follow,
3093             ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
3094             ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
3095             ["block"] = MyCommon.EVENTTYPE.Block,
3096             ["unblock"] = MyCommon.EVENTTYPE.Unblock,
3097             ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
3098             ["deleted"] = MyCommon.EVENTTYPE.Deleted,
3099             ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
3100             ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
3101             ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
3102             ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
3103             ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
3104             ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
3105             ["mute"] = MyCommon.EVENTTYPE.Mute,
3106             ["unmute"] = MyCommon.EVENTTYPE.Unmute,
3107             ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
3108         };
3109
3110         public bool IsUserstreamDataReceived
3111         {
3112             get
3113             {
3114                 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
3115             }
3116         }
3117
3118         private void userStream_StatusArrived(string line)
3119         {
3120             this._lastUserstreamDataReceived = DateTime.Now;
3121             if (string.IsNullOrEmpty(line)) return;
3122
3123             if (line.First() != '{' || line.Last() != '}')
3124             {
3125                 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
3126                 return;
3127             }
3128
3129             var isDm = false;
3130
3131             try
3132             {
3133                 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
3134                 {
3135                     var xElm = XElement.Load(jsonReader);
3136                     if (xElm.Element("friends") != null)
3137                     {
3138                         Debug.WriteLine("friends");
3139                         return;
3140                     }
3141                     else if (xElm.Element("delete") != null)
3142                     {
3143                         Debug.WriteLine("delete");
3144                         Int64 id;
3145                         XElement idElm;
3146                         if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
3147                         {
3148                             id = 0;
3149                             long.TryParse(idElm.Value, out id);
3150
3151                             this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
3152                         }
3153                         else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
3154                         {
3155                             id = 0;
3156                             long.TryParse(idElm.Value, out id);
3157
3158                             this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
3159                         }
3160                         else
3161                         {
3162                             MyCommon.TraceOut("delete:" + line);
3163                             return;
3164                         }
3165                         for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
3166                         {
3167                             var sEvt = this.StoredEvent[i];
3168                             if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
3169                             {
3170                                 this.StoredEvent.RemoveAt(i);
3171                             }
3172                         }
3173                         return;
3174                     }
3175                     else if (xElm.Element("limit") != null)
3176                     {
3177                         Debug.WriteLine(line);
3178                         return;
3179                     }
3180                     else if (xElm.Element("event") != null)
3181                     {
3182                         Debug.WriteLine("event: " + xElm.Element("event").Value);
3183                         CreateEventFromJson(line);
3184                         return;
3185                     }
3186                     else if (xElm.Element("direct_message") != null)
3187                     {
3188                         Debug.WriteLine("direct_message");
3189                         isDm = true;
3190                     }
3191                     else if (xElm.Element("retweeted_status") != null)
3192                     {
3193                         var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
3194                         var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
3195
3196                         // 自分に関係しないリツイートの場合は無視する
3197                         var selfUserId = this.UserId.ToString();
3198                         if (sourceUserId == selfUserId || targetUserId == selfUserId)
3199                         {
3200                             // 公式 RT をイベントとしても扱う
3201                             var evt = CreateEventFromRetweet(xElm);
3202                             if (evt != null)
3203                             {
3204                                 this.StoredEvent.Insert(0, evt);
3205
3206                                 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
3207                             }
3208                         }
3209
3210                         // 従来通り公式 RT の表示も行うため return しない
3211                     }
3212                     else if (xElm.Element("scrub_geo") != null)
3213                     {
3214                         try
3215                         {
3216                             TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
3217                                                                         long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
3218                         }
3219                         catch(Exception)
3220                         {
3221                             MyCommon.TraceOut("scrub_geo:" + line);
3222                         }
3223                         return;
3224                     }
3225                 }
3226
3227                 if (isDm)
3228                 {
3229                     CreateDirectMessagesFromJson(line, MyCommon.WORKERTYPE.UserStream, false);
3230                 }
3231                 else
3232                 {
3233                     CreatePostsFromJson("[" + line + "]", MyCommon.WORKERTYPE.Timeline, null, false);
3234                 }
3235             }
3236             catch (WebApiException ex)
3237             {
3238                 MyCommon.TraceOut(ex);
3239                 return;
3240             }
3241             catch(NullReferenceException)
3242             {
3243                 MyCommon.TraceOut("NullRef StatusArrived: " + line);
3244             }
3245
3246             this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
3247         }
3248
3249         /// <summary>
3250         /// UserStreamsから受信した公式RTをイベントに変換します
3251         /// </summary>
3252         private FormattedEvent CreateEventFromRetweet(XElement xElm)
3253         {
3254             return new FormattedEvent
3255             {
3256                 Eventtype = MyCommon.EVENTTYPE.Retweet,
3257                 Event = "retweet",
3258                 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
3259                 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
3260                 Username = xElm.XPathSelectElement("/user/screen_name").Value,
3261                 Target = string.Format("@{0}:{1}", new[]
3262                 {
3263                     xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
3264                     WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
3265                 }),
3266                 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
3267             };
3268         }
3269
3270         private void CreateEventFromJson(string content)
3271         {
3272             TwitterStreamEvent eventData = null;
3273             try
3274             {
3275                 eventData = TwitterStreamEvent.ParseJson(content);
3276             }
3277             catch(SerializationException ex)
3278             {
3279                 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
3280             }
3281             catch(Exception ex)
3282             {
3283                 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
3284             }
3285
3286             var evt = new FormattedEvent();
3287             evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
3288             evt.Event = eventData.Event;
3289             evt.Username = eventData.Source.ScreenName;
3290             evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
3291
3292             MyCommon.EVENTTYPE eventType;
3293             eventTable.TryGetValue(eventData.Event, out eventType);
3294             evt.Eventtype = eventType;
3295
3296             TwitterStreamEvent<TwitterStatus> tweetEvent;
3297
3298             switch (eventData.Event)
3299             {
3300                 case "access_revoked":
3301                 case "access_unrevoked":
3302                 case "user_delete":
3303                 case "user_suspend":
3304                     return;
3305                 case "follow":
3306                     if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
3307                     {
3308                         if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
3309                     }
3310                     else
3311                     {
3312                         return;    //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
3313                     }
3314                     evt.Target = "";
3315                     break;
3316                 case "unfollow":
3317                     evt.Target = "@" + eventData.Target.ScreenName;
3318                     break;
3319                 case "favorited_retweet":
3320                 case "retweeted_retweet":
3321                     return;
3322                 case "favorite":
3323                 case "unfavorite":
3324                     tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
3325                     evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
3326                     evt.Id = tweetEvent.TargetObject.Id;
3327
3328                     if (SettingCommon.Instance.IsRemoveSameEvent)
3329                     {
3330                         if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
3331                             return;
3332                     }
3333
3334                     var tabinfo = TabInformations.GetInstance();
3335
3336                     PostClass post;
3337                     var statusId = tweetEvent.TargetObject.Id;
3338                     if (!tabinfo.Posts.TryGetValue(statusId, out post))
3339                         break;
3340
3341                     if (eventData.Event == "favorite")
3342                     {
3343                         var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
3344                         if (!favTab.Contains(post.StatusId))
3345                             favTab.AddPostImmediately(post.StatusId, post.IsRead);
3346
3347                         if (tweetEvent.Source.Id == this.UserId)
3348                         {
3349                             post.IsFav = true;
3350                         }
3351                         else if (tweetEvent.Target.Id == this.UserId)
3352                         {
3353                             post.FavoritedCount++;
3354
3355                             if (SettingCommon.Instance.FavEventUnread)
3356                                 tabinfo.SetReadAllTab(post.StatusId, read: false);
3357                         }
3358                     }
3359                     else // unfavorite
3360                     {
3361                         if (tweetEvent.Source.Id == this.UserId)
3362                         {
3363                             post.IsFav = false;
3364                         }
3365                         else if (tweetEvent.Target.Id == this.UserId)
3366                         {
3367                             post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
3368                         }
3369                     }
3370                     break;
3371                 case "quoted_tweet":
3372                     if (evt.IsMe) return;
3373
3374                     tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
3375                     evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
3376                     evt.Id = tweetEvent.TargetObject.Id;
3377
3378                     if (SettingCommon.Instance.IsRemoveSameEvent)
3379                     {
3380                         if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
3381                             return;
3382                     }
3383                     break;
3384                 case "list_member_added":
3385                 case "list_member_removed":
3386                 case "list_created":
3387                 case "list_destroyed":
3388                 case "list_updated":
3389                 case "list_user_subscribed":
3390                 case "list_user_unsubscribed":
3391                     var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
3392                     evt.Target = listEvent.TargetObject.FullName;
3393                     break;
3394                 case "block":
3395                     if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
3396                     evt.Target = "";
3397                     break;
3398                 case "unblock":
3399                     if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
3400                     evt.Target = "";
3401                     break;
3402                 case "user_update":
3403                     evt.Target = "";
3404                     break;
3405                 
3406                 // Mute / Unmute
3407                 case "mute":
3408                     evt.Target = "@" + eventData.Target.ScreenName;
3409                     if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
3410                     {
3411                         TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
3412                     }
3413                     break;
3414                 case "unmute":
3415                     evt.Target = "@" + eventData.Target.ScreenName;
3416                     if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
3417                     {
3418                         TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
3419                     }
3420                     break;
3421
3422                 default:
3423                     MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
3424                     break;
3425             }
3426             this.StoredEvent.Insert(0, evt);
3427
3428             this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
3429         }
3430
3431         private void userStream_Started()
3432         {
3433             this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
3434         }
3435
3436         private void userStream_Stopped()
3437         {
3438             this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
3439         }
3440
3441         public bool UserStreamEnabled
3442         {
3443             get
3444             {
3445                 return userStream == null ? false : userStream.Enabled;
3446             }
3447         }
3448
3449         public void StartUserStream()
3450         {
3451             if (userStream != null)
3452             {
3453                 StopUserStream();
3454             }
3455             userStream = new TwitterUserstream(twCon);
3456             userStream.StatusArrived += userStream_StatusArrived;
3457             userStream.Started += userStream_Started;
3458             userStream.Stopped += userStream_Stopped;
3459             userStream.Start(this.AllAtReply, this.TrackWord);
3460         }
3461
3462         public void StopUserStream()
3463         {
3464             userStream?.Dispose();
3465             userStream = null;
3466             if (!MyCommon._endingFlag)
3467             {
3468                 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
3469             }
3470         }
3471
3472         public void ReconnectUserStream()
3473         {
3474             if (userStream != null)
3475             {
3476                 this.StartUserStream();
3477             }
3478         }
3479
3480         private class TwitterUserstream : IDisposable
3481         {
3482             public event Action<string> StatusArrived;
3483             public event Action Stopped;
3484             public event Action Started;
3485             private HttpTwitter twCon;
3486
3487             private Thread _streamThread;
3488             private bool _streamActive;
3489
3490             private bool _allAtreplies = false;
3491             private string _trackwords = "";
3492
3493             public TwitterUserstream(HttpTwitter twitterConnection)
3494             {
3495                 twCon = (HttpTwitter)twitterConnection.Clone();
3496             }
3497
3498             public void Start(bool allAtReplies, string trackwords)
3499             {
3500                 this.AllAtReplies = allAtReplies;
3501                 this.TrackWords = trackwords;
3502                 _streamActive = true;
3503                 if (_streamThread != null && _streamThread.IsAlive) return;
3504                 _streamThread = new Thread(UserStreamLoop);
3505                 _streamThread.Name = "UserStreamReceiver";
3506                 _streamThread.IsBackground = true;
3507                 _streamThread.Start();
3508             }
3509
3510             public bool Enabled
3511             {
3512                 get
3513                 {
3514                     return _streamActive;
3515                 }
3516             }
3517
3518             public bool AllAtReplies
3519             {
3520                 get
3521                 {
3522                     return _allAtreplies;
3523                 }
3524                 set
3525                 {
3526                     _allAtreplies = value;
3527                 }
3528             }
3529
3530             public string TrackWords
3531             {
3532                 get
3533                 {
3534                     return _trackwords;
3535                 }
3536                 set
3537                 {
3538                     _trackwords = value;
3539                 }
3540             }
3541
3542             private void UserStreamLoop()
3543             {
3544                 var sleepSec = 0;
3545                 do
3546                 {
3547                     Stream st = null;
3548                     StreamReader sr = null;
3549                     try
3550                     {
3551                         if (!MyCommon.IsNetworkAvailable())
3552                         {
3553                             sleepSec = 30;
3554                             continue;
3555                         }
3556
3557                         Started?.Invoke();
3558
3559                         var res = twCon.UserStream(ref st, _allAtreplies, _trackwords, Networking.GetUserAgentString());
3560
3561                         switch (res)
3562                         {
3563                             case HttpStatusCode.OK:
3564                                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3565                                 break;
3566                             case HttpStatusCode.Unauthorized:
3567                                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
3568                                 sleepSec = 120;
3569                                 continue;
3570                         }
3571
3572                         if (st == null)
3573                         {
3574                             sleepSec = 30;
3575                             //MyCommon.TraceOut("Stop:stream is null")
3576                             continue;
3577                         }
3578
3579                         sr = new StreamReader(st);
3580
3581                         while (_streamActive && !sr.EndOfStream && Twitter.AccountState == MyCommon.ACCOUNT_STATE.Valid)
3582                         {
3583                             StatusArrived?.Invoke(sr.ReadLine());
3584                             //this.LastTime = Now;
3585                         }
3586
3587                         if (sr.EndOfStream || Twitter.AccountState == MyCommon.ACCOUNT_STATE.Invalid)
3588                         {
3589                             sleepSec = 30;
3590                             //MyCommon.TraceOut("Stop:EndOfStream")
3591                             continue;
3592                         }
3593                         break;
3594                     }
3595                     catch(WebException ex)
3596                     {
3597                         if (ex.Status == WebExceptionStatus.Timeout)
3598                         {
3599                             sleepSec = 30;                        //MyCommon.TraceOut("Stop:Timeout")
3600                         }
3601                         else if (ex.Response != null && (int)((HttpWebResponse)ex.Response).StatusCode == 420)
3602                         {
3603                             //MyCommon.TraceOut("Stop:Connection Limit")
3604                             break;
3605                         }
3606                         else
3607                         {
3608                             sleepSec = 30;
3609                             //MyCommon.TraceOut("Stop:WebException " + ex.Status.ToString())
3610                         }
3611                     }
3612                     catch(ThreadAbortException)
3613                     {
3614                         break;
3615                     }
3616                     catch(IOException)
3617                     {
3618                         sleepSec = 30;
3619                         //MyCommon.TraceOut("Stop:IOException with Active." + Environment.NewLine + ex.Message)
3620                     }
3621                     catch(ArgumentException ex)
3622                     {
3623                         //System.ArgumentException: ストリームを読み取れませんでした。
3624                         //サーバー側もしくは通信経路上で切断された場合?タイムアウト頻発後発生
3625                         sleepSec = 30;
3626                         MyCommon.TraceOut(ex, "Stop:ArgumentException");
3627                     }
3628                     catch(Exception ex)
3629                     {
3630                         MyCommon.TraceOut("Stop:Exception." + Environment.NewLine + ex.Message);
3631                         MyCommon.ExceptionOut(ex);
3632                         sleepSec = 30;
3633                     }
3634                     finally
3635                     {
3636                         if (_streamActive)
3637                         {
3638                             Stopped?.Invoke();
3639                         }
3640                         twCon.RequestAbort();
3641                         sr?.Close();
3642                         if (sleepSec > 0)
3643                         {
3644                             var ms = 0;
3645                             while (_streamActive && ms < sleepSec * 1000)
3646                             {
3647                                 Thread.Sleep(500);
3648                                 ms += 500;
3649                             }
3650                         }
3651                         sleepSec = 0;
3652                     }
3653                 } while (this._streamActive);
3654
3655                 if (_streamActive)
3656                 {
3657                     Stopped?.Invoke();
3658                 }
3659                 MyCommon.TraceOut("Stop:EndLoop");
3660             }
3661
3662 #region "IDisposable Support"
3663             private bool disposedValue; // 重複する呼び出しを検出するには
3664
3665             // IDisposable
3666             protected virtual void Dispose(bool disposing)
3667             {
3668                 if (!this.disposedValue)
3669                 {
3670                     if (disposing)
3671                     {
3672                         _streamActive = false;
3673                         if (_streamThread != null && _streamThread.IsAlive)
3674                         {
3675                             _streamThread.Abort();
3676                         }
3677                     }
3678                 }
3679                 this.disposedValue = true;
3680             }
3681
3682             //protected Overrides void Finalize()
3683             //{
3684             //    // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3685             //    Dispose(false)
3686             //    MyBase.Finalize()
3687             //}
3688
3689             // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
3690             public void Dispose()
3691             {
3692                 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3693                 Dispose(true);
3694                 GC.SuppressFinalize(this);
3695             }
3696 #endregion
3697
3698         }
3699 #endregion
3700
3701 #region "IDisposable Support"
3702         private bool disposedValue; // 重複する呼び出しを検出するには
3703
3704         // IDisposable
3705         protected virtual void Dispose(bool disposing)
3706         {
3707             if (!this.disposedValue)
3708             {
3709                 if (disposing)
3710                 {
3711                     this.StopUserStream();
3712                 }
3713             }
3714             this.disposedValue = true;
3715         }
3716
3717         //protected Overrides void Finalize()
3718         //{
3719         //    // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3720         //    Dispose(false)
3721         //    MyBase.Finalize()
3722         //}
3723
3724         // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
3725         public void Dispose()
3726         {
3727             // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3728             Dispose(true);
3729             GC.SuppressFinalize(this);
3730         }
3731 #endregion
3732     }
3733
3734     public class PostDeletedEventArgs : EventArgs
3735     {
3736         public long StatusId { get; }
3737
3738         public PostDeletedEventArgs(long statusId)
3739         {
3740             this.StatusId = statusId;
3741         }
3742     }
3743
3744     public class UserStreamEventReceivedEventArgs : EventArgs
3745     {
3746         public Twitter.FormattedEvent EventData { get; }
3747
3748         public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
3749         {
3750             this.EventData = eventData;
3751         }
3752     }
3753 }