OSDN Git Service

IEnumerable.OfType<T>()の直後にnullチェックをしている箇所を削除
[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                 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1635                 .ToArray();
1636
1637             //Source整形
1638             var source = ParseSource(sourceHtml);
1639             post.Source = source.Item1;
1640             post.SourceUri = source.Item2;
1641
1642             post.IsReply = post.ReplyToList.Contains(_uname);
1643             post.IsExcludeReply = false;
1644
1645             if (post.IsMe)
1646             {
1647                 post.IsOwl = false;
1648             }
1649             else
1650             {
1651                 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
1652             }
1653
1654             post.IsDm = false;
1655             return post;
1656         }
1657
1658         /// <summary>
1659         /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
1660         /// </summary>
1661         public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
1662         {
1663             var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
1664
1665             return GetQuoteTweetStatusIds(urls);
1666         }
1667
1668         public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
1669         {
1670             foreach (var url in urls)
1671             {
1672                 var match = Twitter.StatusUrlRegex.Match(url);
1673                 if (match.Success)
1674                 {
1675                     long statusId;
1676                     if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
1677                         yield return statusId;
1678                 }
1679             }
1680         }
1681
1682         private long? CreatePostsFromJson(string content, MyCommon.WORKERTYPE gType, TabClass tab, bool read)
1683         {
1684             TwitterStatus[] items;
1685             try
1686             {
1687                 items = TwitterStatus.ParseJsonArray(content);
1688             }
1689             catch(SerializationException ex)
1690             {
1691                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1692                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1693             }
1694             catch(Exception ex)
1695             {
1696                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1697                 throw new WebApiException("Invalid Json!", content, ex);
1698             }
1699
1700             long? minimumId = null;
1701
1702             foreach (var status in items)
1703             {
1704                 PostClass post = null;
1705                 post = CreatePostsFromStatusData(status);
1706                 if (post == null) continue;
1707
1708                 if (minimumId == null || minimumId.Value > post.StatusId)
1709                     minimumId = post.StatusId;
1710
1711                 //二重取得回避
1712                 lock (LockObj)
1713                 {
1714                     if (tab == null)
1715                     {
1716                         if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1717                     }
1718                     else
1719                     {
1720                         if (tab.Contains(post.StatusId)) continue;
1721                     }
1722                 }
1723
1724                 //RT禁止ユーザーによるもの
1725                 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
1726                     post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
1727
1728                 post.IsRead = read;
1729                 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1730
1731                 //非同期アイコン取得&StatusDictionaryに追加
1732                 if (tab != null && tab.IsInnerStorageTabType)
1733                     tab.AddPostToInnerStorage(post);
1734                 else
1735                     TabInformations.GetInstance().AddPost(post);
1736             }
1737
1738             return minimumId;
1739         }
1740
1741         private long? CreatePostsFromSearchJson(string content, TabClass tab, bool read, int count, bool more)
1742         {
1743             TwitterSearchResult items;
1744             try
1745             {
1746                 items = TwitterSearchResult.ParseJson(content);
1747             }
1748             catch (SerializationException ex)
1749             {
1750                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1751                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1752             }
1753             catch (Exception ex)
1754             {
1755                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1756                 throw new WebApiException("Invalid Json!", content, ex);
1757             }
1758
1759             long? minimumId = null;
1760
1761             foreach (var result in items.Statuses)
1762             {
1763                 PostClass post = null;
1764                 post = CreatePostsFromStatusData(result);
1765
1766                 if (post == null)
1767                 {
1768                     // Search API は相変わらずぶっ壊れたデータを返すことがあるため、必要なデータが欠如しているものは取得し直す
1769                     try
1770                     {
1771                         post = this.GetStatusApi(read, result.Id);
1772                     }
1773                     catch (WebApiException)
1774                     {
1775                         continue;
1776                     }
1777                 }
1778
1779                 if (minimumId == null || minimumId.Value > post.StatusId)
1780                     minimumId = post.StatusId;
1781
1782                 if (!more && post.StatusId > tab.SinceId) tab.SinceId = post.StatusId;
1783                 //二重取得回避
1784                 lock (LockObj)
1785                 {
1786                     if (tab == null)
1787                     {
1788                         if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1789                     }
1790                     else
1791                     {
1792                         if (tab.Contains(post.StatusId)) continue;
1793                     }
1794                 }
1795
1796                 post.IsRead = read;
1797                 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
1798
1799                 //非同期アイコン取得&StatusDictionaryに追加
1800                 if (tab != null && tab.IsInnerStorageTabType)
1801                     tab.AddPostToInnerStorage(post);
1802                 else
1803                     TabInformations.GetInstance().AddPost(post);
1804             }
1805
1806             return minimumId;
1807         }
1808
1809         private void CreateFavoritePostsFromJson(string content, bool read)
1810         {
1811             TwitterStatus[] item;
1812             try
1813             {
1814                 item = TwitterStatus.ParseJsonArray(content);
1815             }
1816             catch (SerializationException ex)
1817             {
1818                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1819                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1820             }
1821             catch (Exception ex)
1822             {
1823                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1824                 throw new WebApiException("Invalid Json!", content, ex);
1825             }
1826
1827             var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1828
1829             foreach (var status in item)
1830             {
1831                 //二重取得回避
1832                 lock (LockObj)
1833                 {
1834                     if (favTab.Contains(status.Id)) continue;
1835                 }
1836
1837                 var post = CreatePostsFromStatusData(status, true);
1838                 if (post == null) continue;
1839
1840                 post.IsRead = read;
1841
1842                 TabInformations.GetInstance().AddPost(post);
1843             }
1844         }
1845
1846         public void GetListStatus(bool read,
1847                                 TabClass tab,
1848                                 bool more,
1849                                 bool startup)
1850         {
1851             HttpStatusCode res;
1852             var content = "";
1853             var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
1854
1855             try
1856             {
1857                 if (more)
1858                 {
1859                     res = twCon.GetListsStatuses(tab.ListInfo.UserId, tab.ListInfo.Id, count, tab.OldestId, null, SettingCommon.Instance.IsListsIncludeRts, ref content);
1860                 }
1861                 else
1862                 {
1863                     res = twCon.GetListsStatuses(tab.ListInfo.UserId, tab.ListInfo.Id, count, null, null, SettingCommon.Instance.IsListsIncludeRts, ref content);
1864                 }
1865             }
1866             catch(Exception ex)
1867             {
1868                 throw new WebApiException("Err:" + ex.Message, ex);
1869             }
1870
1871             this.CheckStatusCode(res, content);
1872
1873             var minimumId = CreatePostsFromJson(content, MyCommon.WORKERTYPE.List, tab, read);
1874
1875             if (minimumId != null)
1876                 tab.OldestId = minimumId.Value;
1877         }
1878
1879         /// <summary>
1880         /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1881         /// </summary>
1882         /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1883         internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1884         {
1885             if (!posts.ContainsKey(startStatusId))
1886                 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1887
1888             var nextPost = posts[startStatusId];
1889             while (nextPost.InReplyToStatusId != null)
1890             {
1891                 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1892                     break;
1893                 nextPost = posts[nextPost.InReplyToStatusId.Value];
1894             }
1895
1896             return nextPost;
1897         }
1898
1899         public void GetRelatedResult(bool read, TabClass tab)
1900         {
1901             var relPosts = new Dictionary<Int64, PostClass>();
1902             if (tab.RelationTargetPost.TextFromApi.Contains("@") && tab.RelationTargetPost.InReplyToStatusId == null)
1903             {
1904                 //検索結果対応
1905                 var p = TabInformations.GetInstance()[tab.RelationTargetPost.StatusId];
1906                 if (p != null && p.InReplyToStatusId != null)
1907                 {
1908                     tab.RelationTargetPost = p;
1909                 }
1910                 else
1911                 {
1912                     p = this.GetStatusApi(read, tab.RelationTargetPost.StatusId);
1913                     tab.RelationTargetPost = p;
1914                 }
1915             }
1916             relPosts.Add(tab.RelationTargetPost.StatusId, tab.RelationTargetPost);
1917
1918             Exception lastException = null;
1919
1920             // in_reply_to_status_id を使用してリプライチェインを辿る
1921             var nextPost = FindTopOfReplyChain(relPosts, tab.RelationTargetPost.StatusId);
1922             var loopCount = 1;
1923             while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1924             {
1925                 var inReplyToId = nextPost.InReplyToStatusId.Value;
1926
1927                 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1928                 if (inReplyToPost == null)
1929                 {
1930                     try
1931                     {
1932                         inReplyToPost = this.GetStatusApi(read, inReplyToId);
1933                     }
1934                     catch (WebApiException ex)
1935                     {
1936                         lastException = ex;
1937                         break;
1938                     }
1939                 }
1940
1941                 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1942
1943                 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1944             }
1945
1946             //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1947             var text = tab.RelationTargetPost.Text;
1948             var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1949                 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1950             foreach (var _match in ma)
1951             {
1952                 Int64 _statusId;
1953                 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1954                 {
1955                     if (relPosts.ContainsKey(_statusId))
1956                         continue;
1957
1958                     var p = TabInformations.GetInstance()[_statusId];
1959                     if (p == null)
1960                     {
1961                         try
1962                         {
1963                             p = this.GetStatusApi(read, _statusId);
1964                         }
1965                         catch (WebApiException ex)
1966                         {
1967                             lastException = ex;
1968                             break;
1969                         }
1970                     }
1971
1972                     if (p != null)
1973                         relPosts.Add(p.StatusId, p);
1974                 }
1975             }
1976
1977             relPosts.Values.ToList().ForEach(p =>
1978             {
1979                 if (p.IsMe && !read && this._readOwnPost)
1980                     p.IsRead = true;
1981                 else
1982                     p.IsRead = read;
1983
1984                 tab.AddPostToInnerStorage(p);
1985             });
1986
1987             if (lastException != null)
1988                 throw new WebApiException(lastException.Message, lastException);
1989         }
1990
1991         public void GetSearch(bool read,
1992                             TabClass tab,
1993                             bool more)
1994         {
1995             HttpStatusCode res;
1996             var content = "";
1997             var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1998             long? maxId = null;
1999             long? sinceId = null;
2000             if (more)
2001             {
2002                 maxId = tab.OldestId - 1;
2003             }
2004             else
2005             {
2006                 sinceId = tab.SinceId;
2007             }
2008
2009             try
2010             {
2011                 // TODO:一時的に40>100件に 件数変更UI作成の必要あり
2012                 res = twCon.Search(tab.SearchWords, tab.SearchLang, count, maxId, sinceId, ref content);
2013             }
2014             catch(Exception ex)
2015             {
2016                 throw new WebApiException("Err:" + ex.Message, ex);
2017             }
2018             switch (res)
2019             {
2020                 case HttpStatusCode.BadRequest:
2021                     throw new WebApiException("Invalid query", content);
2022                 case HttpStatusCode.NotFound:
2023                     throw new WebApiException("Invalid query", content);
2024                 case HttpStatusCode.PaymentRequired: //API Documentには420と書いてあるが、該当コードがないので402にしてある
2025                     throw new WebApiException("Search API Limit?", content);
2026                 case HttpStatusCode.OK:
2027                     break;
2028                 default:
2029                     throw new WebApiException("Err:" + res.ToString() + "(" + MethodBase.GetCurrentMethod().Name + ")", content);
2030             }
2031
2032             if (!TabInformations.GetInstance().ContainsTab(tab))
2033                 return;
2034
2035             var minimumId =  this.CreatePostsFromSearchJson(content, tab, read, count, more);
2036
2037             if (minimumId != null)
2038                 tab.OldestId = minimumId.Value;
2039         }
2040
2041         private void CreateDirectMessagesFromJson(string content, MyCommon.WORKERTYPE gType, bool read)
2042         {
2043             TwitterDirectMessage[] item;
2044             try
2045             {
2046                 if (gType == MyCommon.WORKERTYPE.UserStream)
2047                 {
2048                     item = new[] { TwitterStreamEventDirectMessage.ParseJson(content).DirectMessage };
2049                 }
2050                 else
2051                 {
2052                     item = TwitterDirectMessage.ParseJsonArray(content);
2053                 }
2054             }
2055             catch(SerializationException ex)
2056             {
2057                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2058                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
2059             }
2060             catch(Exception ex)
2061             {
2062                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2063                 throw new WebApiException("Invalid Json!", content, ex);
2064             }
2065
2066             foreach (var message in item)
2067             {
2068                 var post = new PostClass();
2069                 try
2070                 {
2071                     post.StatusId = message.Id;
2072                     if (gType != MyCommon.WORKERTYPE.UserStream)
2073                     {
2074                         if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
2075                         {
2076                             if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
2077                         }
2078                         else
2079                         {
2080                             if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
2081                         }
2082                     }
2083
2084                     //二重取得回避
2085                     lock (LockObj)
2086                     {
2087                         if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
2088                     }
2089                     //sender_id
2090                     //recipient_id
2091                     post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
2092                     //本文
2093                     var textFromApi = message.Text;
2094                     //HTMLに整形
2095                     post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
2096                     post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
2097                     post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
2098                     post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
2099                     post.IsFav = false;
2100
2101                     post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
2102
2103                     post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
2104                         .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
2105                         .ToArray();
2106
2107                     //以下、ユーザー情報
2108                     TwitterUser user;
2109                     if (gType == MyCommon.WORKERTYPE.UserStream)
2110                     {
2111                         if (twCon.AuthenticatedUsername.Equals(message.Recipient.ScreenName, StringComparison.CurrentCultureIgnoreCase))
2112                         {
2113                             user = message.Sender;
2114                             post.IsMe = false;
2115                             post.IsOwl = true;
2116                         }
2117                         else
2118                         {
2119                             user = message.Recipient;
2120                             post.IsMe = true;
2121                             post.IsOwl = false;
2122                         }
2123                     }
2124                     else
2125                     {
2126                         if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
2127                         {
2128                             user = message.Sender;
2129                             post.IsMe = false;
2130                             post.IsOwl = true;
2131                         }
2132                         else
2133                         {
2134                             user = message.Recipient;
2135                             post.IsMe = true;
2136                             post.IsOwl = false;
2137                         }
2138                     }
2139
2140                     post.UserId = user.Id;
2141                     post.ScreenName = user.ScreenName;
2142                     post.Nickname = user.Name.Trim();
2143                     post.ImageUrl = user.ProfileImageUrlHttps;
2144                     post.IsProtect = user.Protected;
2145                 }
2146                 catch(Exception ex)
2147                 {
2148                     MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2149                     MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
2150                     continue;
2151                 }
2152
2153                 post.IsRead = read;
2154                 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
2155                 post.IsReply = false;
2156                 post.IsExcludeReply = false;
2157                 post.IsDm = true;
2158
2159                 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
2160                 dmTab.AddPostToInnerStorage(post);
2161             }
2162         }
2163
2164         public void GetDirectMessageApi(bool read,
2165                                 MyCommon.WORKERTYPE gType,
2166                                 bool more)
2167         {
2168             this.CheckAccountState();
2169             this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
2170
2171             HttpStatusCode res;
2172             var content = "";
2173             var count = GetApiResultCount(gType, more, false);
2174
2175             try
2176             {
2177                 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
2178                 {
2179                     if (more)
2180                     {
2181                         res = twCon.DirectMessages(count, minDirectmessage, null, ref content);
2182                     }
2183                     else
2184                     {
2185                         res = twCon.DirectMessages(count, null, null, ref content);
2186                     }
2187                 }
2188                 else
2189                 {
2190                     if (more)
2191                     {
2192                         res = twCon.DirectMessagesSent(count, minDirectmessageSent, null, ref content);
2193                     }
2194                     else
2195                     {
2196                         res = twCon.DirectMessagesSent(count, null, null, ref content);
2197                     }
2198                 }
2199             }
2200             catch(Exception ex)
2201             {
2202                 throw new WebApiException("Err:" + ex.Message, ex);
2203             }
2204
2205             this.CheckStatusCode(res, content);
2206
2207             CreateDirectMessagesFromJson(content, gType, read);
2208         }
2209
2210         public void GetFavoritesApi(bool read,
2211                             bool more)
2212         {
2213             this.CheckAccountState();
2214
2215             HttpStatusCode res;
2216             var content = "";
2217             var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
2218
2219             try
2220             {
2221                 res = twCon.Favorites(count, ref content);
2222             }
2223             catch(Exception ex)
2224             {
2225                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2226             }
2227
2228             this.CheckStatusCode(res, content);
2229
2230             CreateFavoritePostsFromJson(content, read);
2231         }
2232
2233         private string ReplaceTextFromApi(string text, TwitterEntities entities)
2234         {
2235             if (entities != null)
2236             {
2237                 if (entities.Urls != null)
2238                 {
2239                     foreach (var m in entities.Urls)
2240                     {
2241                         if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
2242                     }
2243                 }
2244                 if (entities.Media != null)
2245                 {
2246                     foreach (var m in entities.Media)
2247                     {
2248                         if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
2249                     }
2250                 }
2251             }
2252             return text;
2253         }
2254
2255         /// <summary>
2256         /// フォロワーIDを更新します
2257         /// </summary>
2258         /// <exception cref="WebApiException"/>
2259         public void RefreshFollowerIds()
2260         {
2261             if (MyCommon._endingFlag) return;
2262
2263             var cursor = -1L;
2264             var newFollowerIds = new HashSet<long>();
2265             do
2266             {
2267                 var ret = this.GetFollowerIdsApi(ref cursor);
2268                 newFollowerIds.UnionWith(ret.Ids);
2269                 cursor = ret.NextCursor;
2270             } while (cursor != 0);
2271
2272             this.followerId = newFollowerIds;
2273             TabInformations.GetInstance().RefreshOwl(this.followerId);
2274
2275             this._GetFollowerResult = true;
2276         }
2277
2278         public bool GetFollowersSuccess
2279         {
2280             get
2281             {
2282                 return _GetFollowerResult;
2283             }
2284         }
2285
2286         private TwitterIds GetFollowerIdsApi(ref long cursor)
2287         {
2288             this.CheckAccountState();
2289
2290             HttpStatusCode res;
2291             var content = "";
2292             try
2293             {
2294                 res = twCon.FollowerIds(cursor, ref content);
2295             }
2296             catch(Exception e)
2297             {
2298                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2299             }
2300
2301             this.CheckStatusCode(res, content);
2302
2303             try
2304             {
2305                 var ret = TwitterIds.ParseJson(content);
2306
2307                 if (ret.Ids == null)
2308                 {
2309                     var ex = new WebApiException("Err: ret.id == null (GetFollowerIdsApi)", content);
2310                     MyCommon.ExceptionOut(ex);
2311                     throw ex;
2312                 }
2313
2314                 return ret;
2315             }
2316             catch(SerializationException e)
2317             {
2318                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2319                 MyCommon.TraceOut(ex);
2320                 throw ex;
2321             }
2322             catch(Exception e)
2323             {
2324                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2325                 MyCommon.TraceOut(ex);
2326                 throw ex;
2327             }
2328         }
2329
2330         /// <summary>
2331         /// RT 非表示ユーザーを更新します
2332         /// </summary>
2333         /// <exception cref="WebApiException"/>
2334         public void RefreshNoRetweetIds()
2335         {
2336             if (MyCommon._endingFlag) return;
2337
2338             this.noRTId = this.NoRetweetIdsApi();
2339
2340             this._GetNoRetweetResult = true;
2341         }
2342
2343         private long[] NoRetweetIdsApi()
2344         {
2345             this.CheckAccountState();
2346
2347             HttpStatusCode res;
2348             var content = "";
2349             try
2350             {
2351                 res = twCon.NoRetweetIds(ref content);
2352             }
2353             catch(Exception e)
2354             {
2355                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2356             }
2357
2358             this.CheckStatusCode(res, content);
2359
2360             try
2361             {
2362                 return MyCommon.CreateDataFromJson<long[]>(content);
2363             }
2364             catch(SerializationException e)
2365             {
2366                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2367                 MyCommon.TraceOut(ex);
2368                 throw ex;
2369             }
2370             catch(Exception e)
2371             {
2372                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2373                 MyCommon.TraceOut(ex);
2374                 throw ex;
2375             }
2376         }
2377
2378         public bool GetNoRetweetSuccess
2379         {
2380             get
2381             {
2382                 return _GetNoRetweetResult;
2383             }
2384         }
2385
2386         /// <summary>
2387         /// t.co の文字列長などの設定情報を更新します
2388         /// </summary>
2389         /// <exception cref="WebApiException"/>
2390         public void RefreshConfiguration()
2391         {
2392             this.Configuration = this.ConfigurationApi();
2393         }
2394
2395         private TwitterConfiguration ConfigurationApi()
2396         {
2397             HttpStatusCode res;
2398             var content = "";
2399             try
2400             {
2401                 res = twCon.GetConfiguration(ref content);
2402             }
2403             catch(Exception e)
2404             {
2405                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2406             }
2407
2408             this.CheckStatusCode(res, content);
2409
2410             try
2411             {
2412                 return TwitterConfiguration.ParseJson(content);
2413             }
2414             catch(SerializationException e)
2415             {
2416                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2417                 MyCommon.TraceOut(ex);
2418                 throw ex;
2419             }
2420             catch(Exception e)
2421             {
2422                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2423                 MyCommon.TraceOut(ex);
2424                 throw ex;
2425             }
2426         }
2427
2428         public void GetListsApi()
2429         {
2430             this.CheckAccountState();
2431
2432             HttpStatusCode res;
2433             IEnumerable<ListElement> lists;
2434             var content = "";
2435
2436             try
2437             {
2438                 res = twCon.GetLists(this.Username, ref content);
2439             }
2440             catch (Exception ex)
2441             {
2442                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2443             }
2444
2445             this.CheckStatusCode(res, content);
2446
2447             try
2448             {
2449                 lists = TwitterList.ParseJsonArray(content)
2450                     .Select(x => new ListElement(x, this));
2451             }
2452             catch (SerializationException ex)
2453             {
2454                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2455                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2456             }
2457             catch (Exception ex)
2458             {
2459                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2460                 throw new WebApiException("Err:Invalid Json!", content, ex);
2461             }
2462
2463             try
2464             {
2465                 res = twCon.GetListsSubscriptions(this.Username, ref content);
2466             }
2467             catch (Exception ex)
2468             {
2469                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2470             }
2471
2472             this.CheckStatusCode(res, content);
2473
2474             try
2475             {
2476                 lists = lists.Concat(TwitterList.ParseJsonArray(content)
2477                     .Select(x => new ListElement(x, this)));
2478             }
2479             catch (SerializationException ex)
2480             {
2481                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2482                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2483             }
2484             catch (Exception ex)
2485             {
2486                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2487                 throw new WebApiException("Err:Invalid Json!", content, ex);
2488             }
2489
2490             TabInformations.GetInstance().SubscribableLists = lists.ToList();
2491         }
2492
2493         public void DeleteList(string list_id)
2494         {
2495             HttpStatusCode res;
2496             var content = "";
2497
2498             try
2499             {
2500                 res = twCon.DeleteListID(this.Username, list_id, ref content);
2501             }
2502             catch(Exception ex)
2503             {
2504                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2505             }
2506
2507             this.CheckStatusCode(res, content);
2508         }
2509
2510         public ListElement EditList(string list_id, string new_name, bool isPrivate, string description)
2511         {
2512             HttpStatusCode res;
2513             var content = "";
2514
2515             try
2516             {
2517                 res = twCon.UpdateListID(this.Username, list_id, new_name, isPrivate, description, ref content);
2518             }
2519             catch(Exception ex)
2520             {
2521                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2522             }
2523
2524             this.CheckStatusCode(res, content);
2525
2526             try
2527             {
2528                 var le = TwitterList.ParseJson(content);
2529                 return  new ListElement(le, this);
2530             }
2531             catch(SerializationException ex)
2532             {
2533                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2534                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2535             }
2536             catch(Exception ex)
2537             {
2538                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2539                 throw new WebApiException("Err:Invalid Json!", content, ex);
2540             }
2541         }
2542
2543         public long GetListMembers(string list_id, List<UserInfo> lists, long cursor)
2544         {
2545             this.CheckAccountState();
2546
2547             HttpStatusCode res;
2548             var content = "";
2549             try
2550             {
2551                 res = twCon.GetListMembers(this.Username, list_id, cursor, ref content);
2552             }
2553             catch(Exception ex)
2554             {
2555                 throw new WebApiException("Err:" + ex.Message);
2556             }
2557
2558             this.CheckStatusCode(res, content);
2559
2560             try
2561             {
2562                 var users = TwitterUsers.ParseJson(content);
2563                 Array.ForEach<TwitterUser>(
2564                     users.Users,
2565                     u => lists.Add(new UserInfo(u)));
2566
2567                 return users.NextCursor;
2568             }
2569             catch(SerializationException ex)
2570             {
2571                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2572                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2573             }
2574             catch(Exception ex)
2575             {
2576                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2577                 throw new WebApiException("Err:Invalid Json!", content, ex);
2578             }
2579         }
2580
2581         public void CreateListApi(string listName, bool isPrivate, string description)
2582         {
2583             this.CheckAccountState();
2584
2585             HttpStatusCode res;
2586             var content = "";
2587             try
2588             {
2589                 res = twCon.CreateLists(listName, isPrivate, description, ref content);
2590             }
2591             catch(Exception ex)
2592             {
2593                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2594             }
2595
2596             this.CheckStatusCode(res, content);
2597
2598             try
2599             {
2600                 var le = TwitterList.ParseJson(content);
2601                 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(le, this));
2602             }
2603             catch(SerializationException ex)
2604             {
2605                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2606                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2607             }
2608             catch(Exception ex)
2609             {
2610                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2611                 throw new WebApiException("Err:Invalid Json!", content, ex);
2612             }
2613         }
2614
2615         public bool ContainsUserAtList(string listId, string user)
2616         {
2617             this.CheckAccountState();
2618
2619             HttpStatusCode res;
2620             var content = "";
2621
2622             try
2623             {
2624                 res = this.twCon.ShowListMember(listId, user, ref content);
2625             }
2626             catch(Exception ex)
2627             {
2628                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2629             }
2630
2631             if (res == HttpStatusCode.NotFound)
2632             {
2633                 return false;
2634             }
2635
2636             this.CheckStatusCode(res, content);
2637
2638             try
2639             {
2640                 TwitterUser.ParseJson(content);
2641                 return true;
2642             }
2643             catch(Exception)
2644             {
2645                 return false;
2646             }
2647         }
2648
2649         public void AddUserToList(string listId, string user)
2650         {
2651             HttpStatusCode res;
2652             var content = "";
2653
2654             try
2655             {
2656                 res = twCon.CreateListMembers(listId, user, ref content);
2657             }
2658             catch(Exception ex)
2659             {
2660                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2661             }
2662
2663             this.CheckStatusCode(res, content);
2664         }
2665
2666         public void RemoveUserToList(string listId, string user)
2667         {
2668             HttpStatusCode res;
2669             var content = "";
2670
2671             try
2672             {
2673                 res = twCon.DeleteListMembers(listId, user, ref content);
2674             }
2675             catch(Exception ex)
2676             {
2677                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2678             }
2679
2680             this.CheckStatusCode(res, content);
2681         }
2682
2683         public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
2684         {
2685             if (entities != null)
2686             {
2687                 if (entities.Hashtags != null)
2688                 {
2689                     lock (this.LockObj)
2690                     {
2691                         this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
2692                     }
2693                 }
2694                 if (entities.UserMentions != null)
2695                 {
2696                     foreach (var ent in entities.UserMentions)
2697                     {
2698                         var screenName = ent.ScreenName.ToLowerInvariant();
2699                         if (!AtList.Contains(screenName))
2700                             AtList.Add(screenName);
2701                     }
2702                 }
2703                 if (entities.Media != null)
2704                 {
2705                     if (media != null)
2706                     {
2707                         foreach (var ent in entities.Media)
2708                         {
2709                             if (!media.Any(x => x.Url == ent.MediaUrl))
2710                             {
2711                                 if (ent.VideoInfo != null &&
2712                                     ent.Type == "animated_gif" || ent.Type == "video")
2713                                 {
2714                                     //var videoUrl = ent.VideoInfo.Variants
2715                                     //    .Where(v => v.ContentType == "video/mp4")
2716                                     //    .OrderByDescending(v => v.Bitrate)
2717                                     //    .Select(v => v.Url).FirstOrDefault();
2718                                     media.Add(new MediaInfo(ent.MediaUrl, ent.ExpandedUrl));
2719                                 }
2720                                 else
2721                                     media.Add(new MediaInfo(ent.MediaUrl));
2722                             }
2723                         }
2724                     }
2725                 }
2726             }
2727
2728             // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
2729             text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
2730
2731             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>");
2732             text = PreProcessUrl(text); //IDN置換
2733
2734             return text;
2735         }
2736
2737         private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
2738
2739         /// <summary>
2740         /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
2741         /// </summary>
2742         public static Tuple<string, Uri> ParseSource(string sourceHtml)
2743         {
2744             if (string.IsNullOrEmpty(sourceHtml))
2745                 return Tuple.Create<string, Uri>("", null);
2746
2747             string sourceText;
2748             Uri sourceUri;
2749
2750             // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
2751
2752             var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
2753             if (match.Success)
2754             {
2755                 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
2756                 try
2757                 {
2758                     var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
2759                     sourceUri = new Uri(SourceUriBase, uriStr);
2760                 }
2761                 catch (UriFormatException)
2762                 {
2763                     sourceUri = null;
2764                 }
2765             }
2766             else
2767             {
2768                 sourceText = WebUtility.HtmlDecode(sourceHtml);
2769                 sourceUri = null;
2770             }
2771
2772             return Tuple.Create(sourceText, sourceUri);
2773         }
2774
2775         public TwitterApiStatus GetInfoApi()
2776         {
2777             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
2778
2779             if (MyCommon._endingFlag) return null;
2780
2781             HttpStatusCode res;
2782             var content = "";
2783             try
2784             {
2785                 res = twCon.RateLimitStatus(ref content);
2786             }
2787             catch (Exception)
2788             {
2789                 this.ResetApiStatus();
2790                 return null;
2791             }
2792
2793             this.CheckStatusCode(res, content);
2794
2795             try
2796             {
2797                 MyCommon.TwitterApiInfo.UpdateFromJson(content);
2798                 return MyCommon.TwitterApiInfo;
2799             }
2800             catch (Exception ex)
2801             {
2802                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2803                 MyCommon.TwitterApiInfo.Reset();
2804                 return null;
2805             }
2806         }
2807
2808         /// <summary>
2809         /// ブロック中のユーザーを更新します
2810         /// </summary>
2811         /// <exception cref="WebApiException"/>
2812         public void RefreshBlockIds()
2813         {
2814             if (MyCommon._endingFlag) return;
2815
2816             var cursor = -1L;
2817             var newBlockIds = new HashSet<long>();
2818             do
2819             {
2820                 var ret = this.GetBlockIdsApi(cursor);
2821                 newBlockIds.UnionWith(ret.Ids);
2822                 cursor = ret.NextCursor;
2823             } while (cursor != 0);
2824
2825             newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
2826
2827             TabInformations.GetInstance().BlockIds = newBlockIds;
2828         }
2829
2830         public TwitterIds GetBlockIdsApi(long cursor)
2831         {
2832             this.CheckAccountState();
2833
2834             HttpStatusCode res;
2835             var content = "";
2836             try
2837             {
2838                 res = twCon.GetBlockUserIds(ref content, cursor);
2839             }
2840             catch(Exception e)
2841             {
2842                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2843             }
2844
2845             this.CheckStatusCode(res, content);
2846
2847             try
2848             {
2849                 return TwitterIds.ParseJson(content);
2850             }
2851             catch(SerializationException e)
2852             {
2853                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2854                 MyCommon.TraceOut(ex);
2855                 throw ex;
2856             }
2857             catch(Exception e)
2858             {
2859                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2860                 MyCommon.TraceOut(ex);
2861                 throw ex;
2862             }
2863         }
2864
2865         /// <summary>
2866         /// ミュート中のユーザーIDを更新します
2867         /// </summary>
2868         /// <exception cref="WebApiException"/>
2869         public async Task RefreshMuteUserIdsAsync()
2870         {
2871             if (MyCommon._endingFlag) return;
2872
2873             var ids = await TwitterIds.GetAllItemsAsync(this.GetMuteUserIdsApiAsync)
2874                 .ConfigureAwait(false);
2875
2876             TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
2877         }
2878
2879         public async Task<TwitterIds> GetMuteUserIdsApiAsync(long cursor)
2880         {
2881             var content = "";
2882
2883             try
2884             {
2885                 var res = await Task.Run(() => twCon.GetMuteUserIds(ref content, cursor))
2886                     .ConfigureAwait(false);
2887
2888                 this.CheckStatusCode(res, content);
2889
2890                 return TwitterIds.ParseJson(content);
2891             }
2892             catch (WebException ex)
2893             {
2894                 var ex2 = new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", content, ex);
2895                 MyCommon.TraceOut(ex2);
2896                 throw ex2;
2897             }
2898             catch (SerializationException ex)
2899             {
2900                 var ex2 = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2901                 MyCommon.TraceOut(ex2);
2902                 throw ex2;
2903             }
2904         }
2905
2906         public string[] GetHashList()
2907         {
2908             string[] hashArray;
2909             lock (LockObj)
2910             {
2911                 hashArray = _hashList.ToArray();
2912                 _hashList.Clear();
2913             }
2914             return hashArray;
2915         }
2916
2917         public string AccessToken
2918         {
2919             get
2920             {
2921                 return twCon.AccessToken;
2922             }
2923         }
2924
2925         public string AccessTokenSecret
2926         {
2927             get
2928             {
2929                 return twCon.AccessTokenSecret;
2930             }
2931         }
2932
2933         private void CheckAccountState()
2934         {
2935             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2936                 throw new WebApiException("Auth error. Check your account");
2937         }
2938
2939         private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
2940         {
2941             if (!this.AccessLevel.HasFlag(accessLevelFlags))
2942                 throw new WebApiException("Auth Err:try to re-authorization.");
2943         }
2944
2945         private void CheckStatusCode(HttpStatusCode httpStatus, string responseText,
2946             [CallerMemberName] string callerMethodName = "")
2947         {
2948             if (httpStatus == HttpStatusCode.OK)
2949             {
2950                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2951                 return;
2952             }
2953
2954             if (string.IsNullOrWhiteSpace(responseText))
2955             {
2956                 if (httpStatus == HttpStatusCode.Unauthorized)
2957                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2958
2959                 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")");
2960             }
2961
2962             try
2963             {
2964                 var errors = TwitterError.ParseJson(responseText).Errors;
2965                 if (errors == null || !errors.Any())
2966                 {
2967                     throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2968                 }
2969
2970                 foreach (var error in errors)
2971                 {
2972                     if (error.Code == TwitterErrorCode.InvalidToken ||
2973                         error.Code == TwitterErrorCode.SuspendedAccount)
2974                     {
2975                         Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2976                     }
2977                 }
2978
2979                 throw new WebApiException("Err:" + string.Join(",", errors.Select(x => x.ToString())) + "(" + callerMethodName + ")", responseText);
2980             }
2981             catch (SerializationException) { }
2982
2983             throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2984         }
2985
2986         public int GetTextLengthRemain(string postText)
2987         {
2988             var matchDm = Twitter.DMSendTextRegex.Match(postText);
2989             if (matchDm.Success)
2990                 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
2991
2992             return this.GetTextLengthRemainInternal(postText, isDm: false);
2993         }
2994
2995         private int GetTextLengthRemainInternal(string postText, bool isDm)
2996         {
2997             var textLength = 0;
2998
2999             var pos = 0;
3000             while (pos < postText.Length)
3001             {
3002                 textLength++;
3003
3004                 if (char.IsSurrogatePair(postText, pos))
3005                     pos += 2; // サロゲートペアの場合は2文字分進める
3006                 else
3007                     pos++;
3008             }
3009
3010             var urls = TweetExtractor.ExtractUrls(postText);
3011             foreach (var url in urls)
3012             {
3013                 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
3014                     ? this.Configuration.ShortUrlLengthHttps
3015                     : this.Configuration.ShortUrlLength;
3016
3017                 textLength += shortUrlLength - url.Length;
3018             }
3019
3020             if (isDm)
3021                 return this.Configuration.DmTextCharacterLimit - textLength;
3022             else
3023                 return 140 - textLength;
3024         }
3025
3026
3027 #region "UserStream"
3028         private string trackWord_ = "";
3029         public string TrackWord
3030         {
3031             get
3032             {
3033                 return trackWord_;
3034             }
3035             set
3036             {
3037                 trackWord_ = value;
3038             }
3039         }
3040         private bool allAtReply_ = false;
3041         public bool AllAtReply
3042         {
3043             get
3044             {
3045                 return allAtReply_;
3046             }
3047             set
3048             {
3049                 allAtReply_ = value;
3050             }
3051         }
3052
3053         public event EventHandler NewPostFromStream;
3054         public event EventHandler UserStreamStarted;
3055         public event EventHandler UserStreamStopped;
3056         public event EventHandler<PostDeletedEventArgs> PostDeleted;
3057         public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
3058         private DateTime _lastUserstreamDataReceived;
3059         private TwitterUserstream userStream;
3060
3061         public class FormattedEvent
3062         {
3063             public MyCommon.EVENTTYPE Eventtype { get; set; }
3064             public DateTime CreatedAt { get; set; }
3065             public string Event { get; set; }
3066             public string Username { get; set; }
3067             public string Target { get; set; }
3068             public Int64 Id { get; set; }
3069             public bool IsMe { get; set; }
3070         }
3071
3072         public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
3073         public List<FormattedEvent> StoredEvent
3074         {
3075             get
3076             {
3077                 return storedEvent_;
3078             }
3079             set
3080             {
3081                 storedEvent_ = value;
3082             }
3083         }
3084
3085         private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
3086         {
3087             ["favorite"] = MyCommon.EVENTTYPE.Favorite,
3088             ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
3089             ["follow"] = MyCommon.EVENTTYPE.Follow,
3090             ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
3091             ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
3092             ["block"] = MyCommon.EVENTTYPE.Block,
3093             ["unblock"] = MyCommon.EVENTTYPE.Unblock,
3094             ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
3095             ["deleted"] = MyCommon.EVENTTYPE.Deleted,
3096             ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
3097             ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
3098             ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
3099             ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
3100             ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
3101             ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
3102             ["mute"] = MyCommon.EVENTTYPE.Mute,
3103             ["unmute"] = MyCommon.EVENTTYPE.Unmute,
3104             ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
3105         };
3106
3107         public bool IsUserstreamDataReceived
3108         {
3109             get
3110             {
3111                 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
3112             }
3113         }
3114
3115         private void userStream_StatusArrived(string line)
3116         {
3117             this._lastUserstreamDataReceived = DateTime.Now;
3118             if (string.IsNullOrEmpty(line)) return;
3119
3120             if (line.First() != '{' || line.Last() != '}')
3121             {
3122                 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
3123                 return;
3124             }
3125
3126             var isDm = false;
3127
3128             try
3129             {
3130                 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
3131                 {
3132                     var xElm = XElement.Load(jsonReader);
3133                     if (xElm.Element("friends") != null)
3134                     {
3135                         Debug.WriteLine("friends");
3136                         return;
3137                     }
3138                     else if (xElm.Element("delete") != null)
3139                     {
3140                         Debug.WriteLine("delete");
3141                         Int64 id;
3142                         XElement idElm;
3143                         if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
3144                         {
3145                             id = 0;
3146                             long.TryParse(idElm.Value, out id);
3147
3148                             this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
3149                         }
3150                         else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
3151                         {
3152                             id = 0;
3153                             long.TryParse(idElm.Value, out id);
3154
3155                             this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
3156                         }
3157                         else
3158                         {
3159                             MyCommon.TraceOut("delete:" + line);
3160                             return;
3161                         }
3162                         for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
3163                         {
3164                             var sEvt = this.StoredEvent[i];
3165                             if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
3166                             {
3167                                 this.StoredEvent.RemoveAt(i);
3168                             }
3169                         }
3170                         return;
3171                     }
3172                     else if (xElm.Element("limit") != null)
3173                     {
3174                         Debug.WriteLine(line);
3175                         return;
3176                     }
3177                     else if (xElm.Element("event") != null)
3178                     {
3179                         Debug.WriteLine("event: " + xElm.Element("event").Value);
3180                         CreateEventFromJson(line);
3181                         return;
3182                     }
3183                     else if (xElm.Element("direct_message") != null)
3184                     {
3185                         Debug.WriteLine("direct_message");
3186                         isDm = true;
3187                     }
3188                     else if (xElm.Element("retweeted_status") != null)
3189                     {
3190                         var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
3191                         var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
3192
3193                         // 自分に関係しないリツイートの場合は無視する
3194                         var selfUserId = this.UserId.ToString();
3195                         if (sourceUserId == selfUserId || targetUserId == selfUserId)
3196                         {
3197                             // 公式 RT をイベントとしても扱う
3198                             var evt = CreateEventFromRetweet(xElm);
3199                             if (evt != null)
3200                             {
3201                                 this.StoredEvent.Insert(0, evt);
3202
3203                                 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
3204                             }
3205                         }
3206
3207                         // 従来通り公式 RT の表示も行うため return しない
3208                     }
3209                     else if (xElm.Element("scrub_geo") != null)
3210                     {
3211                         try
3212                         {
3213                             TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
3214                                                                         long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
3215                         }
3216                         catch(Exception)
3217                         {
3218                             MyCommon.TraceOut("scrub_geo:" + line);
3219                         }
3220                         return;
3221                     }
3222                 }
3223
3224                 if (isDm)
3225                 {
3226                     CreateDirectMessagesFromJson(line, MyCommon.WORKERTYPE.UserStream, false);
3227                 }
3228                 else
3229                 {
3230                     CreatePostsFromJson("[" + line + "]", MyCommon.WORKERTYPE.Timeline, null, false);
3231                 }
3232             }
3233             catch (WebApiException ex)
3234             {
3235                 MyCommon.TraceOut(ex);
3236                 return;
3237             }
3238             catch(NullReferenceException)
3239             {
3240                 MyCommon.TraceOut("NullRef StatusArrived: " + line);
3241             }
3242
3243             this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
3244         }
3245
3246         /// <summary>
3247         /// UserStreamsから受信した公式RTをイベントに変換します
3248         /// </summary>
3249         private FormattedEvent CreateEventFromRetweet(XElement xElm)
3250         {
3251             return new FormattedEvent
3252             {
3253                 Eventtype = MyCommon.EVENTTYPE.Retweet,
3254                 Event = "retweet",
3255                 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
3256                 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
3257                 Username = xElm.XPathSelectElement("/user/screen_name").Value,
3258                 Target = string.Format("@{0}:{1}", new[]
3259                 {
3260                     xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
3261                     WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
3262                 }),
3263                 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
3264             };
3265         }
3266
3267         private void CreateEventFromJson(string content)
3268         {
3269             TwitterStreamEvent eventData = null;
3270             try
3271             {
3272                 eventData = TwitterStreamEvent.ParseJson(content);
3273             }
3274             catch(SerializationException ex)
3275             {
3276                 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
3277             }
3278             catch(Exception ex)
3279             {
3280                 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
3281             }
3282
3283             var evt = new FormattedEvent();
3284             evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
3285             evt.Event = eventData.Event;
3286             evt.Username = eventData.Source.ScreenName;
3287             evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
3288
3289             MyCommon.EVENTTYPE eventType;
3290             eventTable.TryGetValue(eventData.Event, out eventType);
3291             evt.Eventtype = eventType;
3292
3293             TwitterStreamEvent<TwitterStatus> tweetEvent;
3294
3295             switch (eventData.Event)
3296             {
3297                 case "access_revoked":
3298                 case "access_unrevoked":
3299                 case "user_delete":
3300                 case "user_suspend":
3301                     return;
3302                 case "follow":
3303                     if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
3304                     {
3305                         if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
3306                     }
3307                     else
3308                     {
3309                         return;    //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
3310                     }
3311                     evt.Target = "";
3312                     break;
3313                 case "unfollow":
3314                     evt.Target = "@" + eventData.Target.ScreenName;
3315                     break;
3316                 case "favorited_retweet":
3317                 case "retweeted_retweet":
3318                     return;
3319                 case "favorite":
3320                 case "unfavorite":
3321                     tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
3322                     evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
3323                     evt.Id = tweetEvent.TargetObject.Id;
3324
3325                     if (SettingCommon.Instance.IsRemoveSameEvent)
3326                     {
3327                         if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
3328                             return;
3329                     }
3330
3331                     var tabinfo = TabInformations.GetInstance();
3332
3333                     PostClass post;
3334                     var statusId = tweetEvent.TargetObject.Id;
3335                     if (!tabinfo.Posts.TryGetValue(statusId, out post))
3336                         break;
3337
3338                     if (eventData.Event == "favorite")
3339                     {
3340                         var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
3341                         if (!favTab.Contains(post.StatusId))
3342                             favTab.AddPostImmediately(post.StatusId, post.IsRead);
3343
3344                         if (tweetEvent.Source.Id == this.UserId)
3345                         {
3346                             post.IsFav = true;
3347                         }
3348                         else if (tweetEvent.Target.Id == this.UserId)
3349                         {
3350                             post.FavoritedCount++;
3351
3352                             if (SettingCommon.Instance.FavEventUnread)
3353                                 tabinfo.SetReadAllTab(post.StatusId, read: false);
3354                         }
3355                     }
3356                     else // unfavorite
3357                     {
3358                         if (tweetEvent.Source.Id == this.UserId)
3359                         {
3360                             post.IsFav = false;
3361                         }
3362                         else if (tweetEvent.Target.Id == this.UserId)
3363                         {
3364                             post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
3365                         }
3366                     }
3367                     break;
3368                 case "quoted_tweet":
3369                     if (evt.IsMe) return;
3370
3371                     tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
3372                     evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
3373                     evt.Id = tweetEvent.TargetObject.Id;
3374
3375                     if (SettingCommon.Instance.IsRemoveSameEvent)
3376                     {
3377                         if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
3378                             return;
3379                     }
3380                     break;
3381                 case "list_member_added":
3382                 case "list_member_removed":
3383                 case "list_created":
3384                 case "list_destroyed":
3385                 case "list_updated":
3386                 case "list_user_subscribed":
3387                 case "list_user_unsubscribed":
3388                     var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
3389                     evt.Target = listEvent.TargetObject.FullName;
3390                     break;
3391                 case "block":
3392                     if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
3393                     evt.Target = "";
3394                     break;
3395                 case "unblock":
3396                     if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
3397                     evt.Target = "";
3398                     break;
3399                 case "user_update":
3400                     evt.Target = "";
3401                     break;
3402                 
3403                 // Mute / Unmute
3404                 case "mute":
3405                     evt.Target = "@" + eventData.Target.ScreenName;
3406                     if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
3407                     {
3408                         TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
3409                     }
3410                     break;
3411                 case "unmute":
3412                     evt.Target = "@" + eventData.Target.ScreenName;
3413                     if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
3414                     {
3415                         TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
3416                     }
3417                     break;
3418
3419                 default:
3420                     MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
3421                     break;
3422             }
3423             this.StoredEvent.Insert(0, evt);
3424
3425             this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
3426         }
3427
3428         private void userStream_Started()
3429         {
3430             this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
3431         }
3432
3433         private void userStream_Stopped()
3434         {
3435             this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
3436         }
3437
3438         public bool UserStreamEnabled
3439         {
3440             get
3441             {
3442                 return userStream == null ? false : userStream.Enabled;
3443             }
3444         }
3445
3446         public void StartUserStream()
3447         {
3448             if (userStream != null)
3449             {
3450                 StopUserStream();
3451             }
3452             userStream = new TwitterUserstream(twCon);
3453             userStream.StatusArrived += userStream_StatusArrived;
3454             userStream.Started += userStream_Started;
3455             userStream.Stopped += userStream_Stopped;
3456             userStream.Start(this.AllAtReply, this.TrackWord);
3457         }
3458
3459         public void StopUserStream()
3460         {
3461             userStream?.Dispose();
3462             userStream = null;
3463             if (!MyCommon._endingFlag)
3464             {
3465                 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
3466             }
3467         }
3468
3469         public void ReconnectUserStream()
3470         {
3471             if (userStream != null)
3472             {
3473                 this.StartUserStream();
3474             }
3475         }
3476
3477         private class TwitterUserstream : IDisposable
3478         {
3479             public event Action<string> StatusArrived;
3480             public event Action Stopped;
3481             public event Action Started;
3482             private HttpTwitter twCon;
3483
3484             private Thread _streamThread;
3485             private bool _streamActive;
3486
3487             private bool _allAtreplies = false;
3488             private string _trackwords = "";
3489
3490             public TwitterUserstream(HttpTwitter twitterConnection)
3491             {
3492                 twCon = (HttpTwitter)twitterConnection.Clone();
3493             }
3494
3495             public void Start(bool allAtReplies, string trackwords)
3496             {
3497                 this.AllAtReplies = allAtReplies;
3498                 this.TrackWords = trackwords;
3499                 _streamActive = true;
3500                 if (_streamThread != null && _streamThread.IsAlive) return;
3501                 _streamThread = new Thread(UserStreamLoop);
3502                 _streamThread.Name = "UserStreamReceiver";
3503                 _streamThread.IsBackground = true;
3504                 _streamThread.Start();
3505             }
3506
3507             public bool Enabled
3508             {
3509                 get
3510                 {
3511                     return _streamActive;
3512                 }
3513             }
3514
3515             public bool AllAtReplies
3516             {
3517                 get
3518                 {
3519                     return _allAtreplies;
3520                 }
3521                 set
3522                 {
3523                     _allAtreplies = value;
3524                 }
3525             }
3526
3527             public string TrackWords
3528             {
3529                 get
3530                 {
3531                     return _trackwords;
3532                 }
3533                 set
3534                 {
3535                     _trackwords = value;
3536                 }
3537             }
3538
3539             private void UserStreamLoop()
3540             {
3541                 var sleepSec = 0;
3542                 do
3543                 {
3544                     Stream st = null;
3545                     StreamReader sr = null;
3546                     try
3547                     {
3548                         if (!MyCommon.IsNetworkAvailable())
3549                         {
3550                             sleepSec = 30;
3551                             continue;
3552                         }
3553
3554                         Started?.Invoke();
3555
3556                         var res = twCon.UserStream(ref st, _allAtreplies, _trackwords, Networking.GetUserAgentString());
3557
3558                         switch (res)
3559                         {
3560                             case HttpStatusCode.OK:
3561                                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3562                                 break;
3563                             case HttpStatusCode.Unauthorized:
3564                                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
3565                                 sleepSec = 120;
3566                                 continue;
3567                         }
3568
3569                         if (st == null)
3570                         {
3571                             sleepSec = 30;
3572                             //MyCommon.TraceOut("Stop:stream is null")
3573                             continue;
3574                         }
3575
3576                         sr = new StreamReader(st);
3577
3578                         while (_streamActive && !sr.EndOfStream && Twitter.AccountState == MyCommon.ACCOUNT_STATE.Valid)
3579                         {
3580                             StatusArrived?.Invoke(sr.ReadLine());
3581                             //this.LastTime = Now;
3582                         }
3583
3584                         if (sr.EndOfStream || Twitter.AccountState == MyCommon.ACCOUNT_STATE.Invalid)
3585                         {
3586                             sleepSec = 30;
3587                             //MyCommon.TraceOut("Stop:EndOfStream")
3588                             continue;
3589                         }
3590                         break;
3591                     }
3592                     catch(WebException ex)
3593                     {
3594                         if (ex.Status == WebExceptionStatus.Timeout)
3595                         {
3596                             sleepSec = 30;                        //MyCommon.TraceOut("Stop:Timeout")
3597                         }
3598                         else if (ex.Response != null && (int)((HttpWebResponse)ex.Response).StatusCode == 420)
3599                         {
3600                             //MyCommon.TraceOut("Stop:Connection Limit")
3601                             break;
3602                         }
3603                         else
3604                         {
3605                             sleepSec = 30;
3606                             //MyCommon.TraceOut("Stop:WebException " + ex.Status.ToString())
3607                         }
3608                     }
3609                     catch(ThreadAbortException)
3610                     {
3611                         break;
3612                     }
3613                     catch(IOException)
3614                     {
3615                         sleepSec = 30;
3616                         //MyCommon.TraceOut("Stop:IOException with Active." + Environment.NewLine + ex.Message)
3617                     }
3618                     catch(ArgumentException ex)
3619                     {
3620                         //System.ArgumentException: ストリームを読み取れませんでした。
3621                         //サーバー側もしくは通信経路上で切断された場合?タイムアウト頻発後発生
3622                         sleepSec = 30;
3623                         MyCommon.TraceOut(ex, "Stop:ArgumentException");
3624                     }
3625                     catch(Exception ex)
3626                     {
3627                         MyCommon.TraceOut("Stop:Exception." + Environment.NewLine + ex.Message);
3628                         MyCommon.ExceptionOut(ex);
3629                         sleepSec = 30;
3630                     }
3631                     finally
3632                     {
3633                         if (_streamActive)
3634                         {
3635                             Stopped?.Invoke();
3636                         }
3637                         twCon.RequestAbort();
3638                         sr?.Close();
3639                         if (sleepSec > 0)
3640                         {
3641                             var ms = 0;
3642                             while (_streamActive && ms < sleepSec * 1000)
3643                             {
3644                                 Thread.Sleep(500);
3645                                 ms += 500;
3646                             }
3647                         }
3648                         sleepSec = 0;
3649                     }
3650                 } while (this._streamActive);
3651
3652                 if (_streamActive)
3653                 {
3654                     Stopped?.Invoke();
3655                 }
3656                 MyCommon.TraceOut("Stop:EndLoop");
3657             }
3658
3659 #region "IDisposable Support"
3660             private bool disposedValue; // 重複する呼び出しを検出するには
3661
3662             // IDisposable
3663             protected virtual void Dispose(bool disposing)
3664             {
3665                 if (!this.disposedValue)
3666                 {
3667                     if (disposing)
3668                     {
3669                         _streamActive = false;
3670                         if (_streamThread != null && _streamThread.IsAlive)
3671                         {
3672                             _streamThread.Abort();
3673                         }
3674                     }
3675                 }
3676                 this.disposedValue = true;
3677             }
3678
3679             //protected Overrides void Finalize()
3680             //{
3681             //    // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3682             //    Dispose(false)
3683             //    MyBase.Finalize()
3684             //}
3685
3686             // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
3687             public void Dispose()
3688             {
3689                 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3690                 Dispose(true);
3691                 GC.SuppressFinalize(this);
3692             }
3693 #endregion
3694
3695         }
3696 #endregion
3697
3698 #region "IDisposable Support"
3699         private bool disposedValue; // 重複する呼び出しを検出するには
3700
3701         // IDisposable
3702         protected virtual void Dispose(bool disposing)
3703         {
3704             if (!this.disposedValue)
3705             {
3706                 if (disposing)
3707                 {
3708                     this.StopUserStream();
3709                 }
3710             }
3711             this.disposedValue = true;
3712         }
3713
3714         //protected Overrides void Finalize()
3715         //{
3716         //    // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3717         //    Dispose(false)
3718         //    MyBase.Finalize()
3719         //}
3720
3721         // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
3722         public void Dispose()
3723         {
3724             // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3725             Dispose(true);
3726             GC.SuppressFinalize(this);
3727         }
3728 #endregion
3729     }
3730
3731     public class PostDeletedEventArgs : EventArgs
3732     {
3733         public long StatusId { get; }
3734
3735         public PostDeletedEventArgs(long statusId)
3736         {
3737             this.StatusId = statusId;
3738         }
3739     }
3740
3741     public class UserStreamEventReceivedEventArgs : EventArgs
3742     {
3743         public Twitter.FormattedEvent EventData { get; }
3744
3745         public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
3746         {
3747             this.EventData = eventData;
3748         }
3749     }
3750 }