OSDN Git Service

PostClass.Mediaに pic.twitter.com などのURLのみを含めるようにする
[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 _restrictFavCheck;
158
159         private bool _readOwnPost;
160         private List<string> _hashList = new List<string>();
161
162         //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
163         private long minHomeTimeline = long.MaxValue;
164         private long minMentions = long.MaxValue;
165         private long minDirectmessage = long.MaxValue;
166         private long minDirectmessageSent = long.MaxValue;
167
168         //private FavoriteQueue favQueue;
169
170         private HttpTwitter twCon = new HttpTwitter();
171
172         //private List<PostClass> _deletemessages = new List<PostClass>();
173
174         public Twitter()
175         {
176             this.Configuration = TwitterConfiguration.DefaultConfiguration();
177         }
178
179         public TwitterApiAccessLevel AccessLevel
180         {
181             get
182             {
183                 return MyCommon.TwitterApiInfo.AccessLevel;
184             }
185         }
186
187         protected void ResetApiStatus()
188         {
189             MyCommon.TwitterApiInfo.Reset();
190         }
191
192         public void Authenticate(string username, string password)
193         {
194             this.ResetApiStatus();
195
196             HttpStatusCode res;
197             var content = "";
198             try
199             {
200                 res = twCon.AuthUserAndPass(username, password, ref content);
201             }
202             catch(Exception ex)
203             {
204                 throw new WebApiException("Err:" + ex.Message, ex);
205             }
206
207             this.CheckStatusCode(res, content);
208
209             _uname = username.ToLower();
210             if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
211         }
212
213         public string StartAuthentication()
214         {
215             //OAuth PIN Flow
216             this.ResetApiStatus();
217             try
218             {
219                 string pinPageUrl = null;
220                 var res = twCon.AuthGetRequestToken(ref pinPageUrl);
221                 if (!res)
222                     throw new WebApiException("Err:Failed to access auth server.");
223
224                 return pinPageUrl;
225             }
226             catch (Exception ex)
227             {
228                 throw new WebApiException("Err:Failed to access auth server.", ex);
229             }
230         }
231
232         public void Authenticate(string pinCode)
233         {
234             this.ResetApiStatus();
235
236             HttpStatusCode res;
237             try
238             {
239                 res = twCon.AuthGetAccessToken(pinCode);
240             }
241             catch (Exception ex)
242             {
243                 throw new WebApiException("Err:Failed to access auth acc server.", ex);
244             }
245
246             this.CheckStatusCode(res, null);
247
248             _uname = Username.ToLower();
249             if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
250         }
251
252         public void ClearAuthInfo()
253         {
254             Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
255             this.ResetApiStatus();
256             twCon.ClearAuthInfo();
257         }
258
259         public void VerifyCredentials()
260         {
261             HttpStatusCode res;
262             var content = "";
263             try
264             {
265                 res = twCon.VerifyCredentials(ref content);
266             }
267             catch (Exception ex)
268             {
269                 throw new WebApiException("Err:" + ex.Message, ex);
270             }
271
272             this.CheckStatusCode(res, content);
273
274             try
275             {
276                 var user = TwitterUser.ParseJson(content);
277
278                 this.twCon.AuthenticatedUserId = user.Id;
279                 this.UpdateUserStats(user);
280             }
281             catch (SerializationException ex)
282             {
283                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
284                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
285             }
286         }
287
288         public void Initialize(string token, string tokenSecret, string username, long userId)
289         {
290             //OAuth認証
291             if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
292             {
293                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
294             }
295             this.ResetApiStatus();
296             twCon.Initialize(token, tokenSecret, username, userId);
297             _uname = username.ToLower();
298             if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
299         }
300
301         public string PreProcessUrl(string orgData)
302         {
303             int posl1;
304             var posl2 = 0;
305             //var IDNConveter = new IdnMapping();
306             var href = "<a href=\"";
307
308             while (true)
309             {
310                 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
311                 {
312                     var urlStr = "";
313                     // IDN展開
314                     posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
315                     posl1 += href.Length;
316                     posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
317                     urlStr = orgData.Substring(posl1, posl2 - posl1);
318
319                     if (!urlStr.StartsWith("http://") && !urlStr.StartsWith("https://") && !urlStr.StartsWith("ftp://"))
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
1133         {
1134             set
1135             {
1136                 _restrictFavCheck = value;
1137             }
1138         }
1139
1140 #region "バージョンアップ"
1141         public void GetTweenBinary(string strVer)
1142         {
1143             try
1144             {
1145                 //本体
1146                 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/Tween" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1147                                                     Path.Combine(MyCommon.settingPath, "TweenNew.exe")))
1148                 {
1149                     throw new WebApiException("Err:Download failed");
1150                 }
1151                 //英語リソース
1152                 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, "en")))
1153                 {
1154                     Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, "en"));
1155                 }
1156                 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenResEn" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1157                                                     Path.Combine(Path.Combine(MyCommon.settingPath, "en"), "Tween.resourcesNew.dll")))
1158                 {
1159                     throw new WebApiException("Err:Download failed");
1160                 }
1161                 //その他言語圏のリソース。取得失敗しても継続
1162                 //UIの言語圏のリソース
1163                 var curCul = "";
1164                 if (!Thread.CurrentThread.CurrentUICulture.IsNeutralCulture)
1165                 {
1166                     var idx = Thread.CurrentThread.CurrentUICulture.Name.LastIndexOf('-');
1167                     if (idx > -1)
1168                     {
1169                         curCul = Thread.CurrentThread.CurrentUICulture.Name.Substring(0, idx);
1170                     }
1171                     else
1172                     {
1173                         curCul = Thread.CurrentThread.CurrentUICulture.Name;
1174                     }
1175                 }
1176                 else
1177                 {
1178                     curCul = Thread.CurrentThread.CurrentUICulture.Name;
1179                 }
1180                 if (!string.IsNullOrEmpty(curCul) && curCul != "en" && curCul != "ja")
1181                 {
1182                     if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul)))
1183                     {
1184                         Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul));
1185                     }
1186                     if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1187                                                         Path.Combine(Path.Combine(MyCommon.settingPath, curCul), "Tween.resourcesNew.dll")))
1188                     {
1189                         //return "Err:Download failed";
1190                     }
1191                 }
1192                 //スレッドの言語圏のリソース
1193                 string curCul2;
1194                 if (!Thread.CurrentThread.CurrentCulture.IsNeutralCulture)
1195                 {
1196                     var idx = Thread.CurrentThread.CurrentCulture.Name.LastIndexOf('-');
1197                     if (idx > -1)
1198                     {
1199                         curCul2 = Thread.CurrentThread.CurrentCulture.Name.Substring(0, idx);
1200                     }
1201                     else
1202                     {
1203                         curCul2 = Thread.CurrentThread.CurrentCulture.Name;
1204                     }
1205                 }
1206                 else
1207                 {
1208                     curCul2 = Thread.CurrentThread.CurrentCulture.Name;
1209                 }
1210                 if (!string.IsNullOrEmpty(curCul2) && curCul2 != "en" && curCul2 != curCul)
1211                 {
1212                     if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul2)))
1213                     {
1214                         Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul2));
1215                     }
1216                     if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul2 + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1217                                                     Path.Combine(Path.Combine(MyCommon.settingPath, curCul2), "Tween.resourcesNew.dll")))
1218                     {
1219                         //return "Err:Download failed";
1220                     }
1221                 }
1222
1223                 //アップデータ
1224                 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenUp3.gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1225                                                     Path.Combine(MyCommon.settingPath, "TweenUp3.exe")))
1226                 {
1227                     throw new WebApiException("Err:Download failed");
1228                 }
1229                 //シリアライザDLL
1230                 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenDll" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
1231                                                     Path.Combine(MyCommon.settingPath, "TweenNew.XmlSerializers.dll")))
1232                 {
1233                     throw new WebApiException("Err:Download failed");
1234                 }
1235             }
1236             catch (Exception ex)
1237             {
1238                 throw new WebApiException("Err:Download failed", ex);
1239             }
1240         }
1241 #endregion
1242
1243         public bool ReadOwnPost
1244         {
1245             get
1246             {
1247                 return _readOwnPost;
1248             }
1249             set
1250             {
1251                 _readOwnPost = value;
1252             }
1253         }
1254
1255         public int FollowersCount { get; private set; }
1256         public int FriendsCount { get; private set; }
1257         public int StatusesCount { get; private set; }
1258         public string Location { get; private set; } = "";
1259         public string Bio { get; private set; } = "";
1260
1261         /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
1262         private void UpdateUserStats(TwitterUser self)
1263         {
1264             this.FollowersCount = self.FollowersCount;
1265             this.FriendsCount = self.FriendsCount;
1266             this.StatusesCount = self.StatusesCount;
1267             this.Location = self.Location;
1268             this.Bio = self.Description;
1269         }
1270
1271         /// <summary>
1272         /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
1273         /// </summary>
1274         public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
1275         {
1276             return count >= 20 && count <= GetMaxApiResultCount(type);
1277         }
1278
1279         /// <summary>
1280         /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
1281         /// </summary>
1282         public static bool VerifyMoreApiResultCount(int count)
1283         {
1284             return count >= 20 && count <= 200;
1285         }
1286
1287         /// <summary>
1288         /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
1289         /// </summary>
1290         public static bool VerifyFirstApiResultCount(int count)
1291         {
1292             return count >= 20 && count <= 200;
1293         }
1294
1295         /// <summary>
1296         /// WORKERTYPEに応じた取得可能な最大件数を取得する
1297         /// </summary>
1298         public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
1299         {
1300             // 参照: REST APIs - 各endpointのcountパラメータ
1301             // https://dev.twitter.com/rest/public
1302             switch (type)
1303             {
1304                 case MyCommon.WORKERTYPE.Timeline:
1305                 case MyCommon.WORKERTYPE.Reply:
1306                 case MyCommon.WORKERTYPE.UserTimeline:
1307                 case MyCommon.WORKERTYPE.Favorites:
1308                 case MyCommon.WORKERTYPE.DirectMessegeRcv:
1309                 case MyCommon.WORKERTYPE.DirectMessegeSnt:
1310                 case MyCommon.WORKERTYPE.List:  // 不明
1311                     return 200;
1312
1313                 case MyCommon.WORKERTYPE.PublicSearch:
1314                     return 100;
1315
1316                 default:
1317                     throw new InvalidOperationException("Invalid type: " + type);
1318             }
1319         }
1320
1321         /// <summary>
1322         /// WORKERTYPEに応じた取得件数を取得する
1323         /// </summary>
1324         public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
1325         {
1326             if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
1327                 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
1328             {
1329                 return 20;
1330             }
1331
1332             if (SettingCommon.Instance.UseAdditionalCount)
1333             {
1334                 switch (type)
1335                 {
1336                     case MyCommon.WORKERTYPE.Favorites:
1337                         if (SettingCommon.Instance.FavoritesCountApi != 0)
1338                             return SettingCommon.Instance.FavoritesCountApi;
1339                         break;
1340                     case MyCommon.WORKERTYPE.List:
1341                         if (SettingCommon.Instance.ListCountApi != 0)
1342                             return SettingCommon.Instance.ListCountApi;
1343                         break;
1344                     case MyCommon.WORKERTYPE.PublicSearch:
1345                         if (SettingCommon.Instance.SearchCountApi != 0)
1346                             return SettingCommon.Instance.SearchCountApi;
1347                         break;
1348                     case MyCommon.WORKERTYPE.UserTimeline:
1349                         if (SettingCommon.Instance.UserTimelineCountApi != 0)
1350                             return SettingCommon.Instance.UserTimelineCountApi;
1351                         break;
1352                 }
1353                 if (more && SettingCommon.Instance.MoreCountApi != 0)
1354                 {
1355                     return Math.Min(SettingCommon.Instance.MoreCountApi, GetMaxApiResultCount(type));
1356                 }
1357                 if (startup && SettingCommon.Instance.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
1358                 {
1359                     return Math.Min(SettingCommon.Instance.FirstCountApi, GetMaxApiResultCount(type));
1360                 }
1361             }
1362
1363             // 上記に当てはまらない場合の共通処理
1364             var count = SettingCommon.Instance.CountApi;
1365
1366             if (type == MyCommon.WORKERTYPE.Reply)
1367                 count = SettingCommon.Instance.CountApiReply;
1368
1369             return Math.Min(count, GetMaxApiResultCount(type));
1370         }
1371
1372         public void GetTimelineApi(bool read,
1373                                 MyCommon.WORKERTYPE gType,
1374                                 bool more,
1375                                 bool startup)
1376         {
1377             this.CheckAccountState();
1378
1379             HttpStatusCode res;
1380             var content = "";
1381             var count = GetApiResultCount(gType, more, startup);
1382
1383             try
1384             {
1385                 if (gType == MyCommon.WORKERTYPE.Timeline)
1386                 {
1387                     if (more)
1388                     {
1389                         res = twCon.HomeTimeline(count, this.minHomeTimeline, null, ref content);
1390                     }
1391                     else
1392                     {
1393                         res = twCon.HomeTimeline(count, null, null, ref content);
1394                     }
1395                 }
1396                 else
1397                 {
1398                     if (more)
1399                     {
1400                         res = twCon.Mentions(count, this.minMentions, null, ref content);
1401                     }
1402                     else
1403                     {
1404                         res = twCon.Mentions(count, null, null, ref content);
1405                     }
1406                 }
1407             }
1408             catch(Exception ex)
1409             {
1410                 throw new WebApiException("Err:" + ex.Message, ex);
1411             }
1412
1413             this.CheckStatusCode(res, content);
1414
1415             var minimumId = CreatePostsFromJson(content, gType, null, read);
1416
1417             if (minimumId != null)
1418             {
1419                 if (gType == MyCommon.WORKERTYPE.Timeline)
1420                     this.minHomeTimeline = minimumId.Value;
1421                 else
1422                     this.minMentions = minimumId.Value;
1423             }
1424         }
1425
1426         public void GetUserTimelineApi(bool read,
1427                                          string userName,
1428                                          TabClass tab,
1429                                          bool more)
1430         {
1431             this.CheckAccountState();
1432
1433             HttpStatusCode res;
1434             var content = "";
1435             var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
1436
1437             try
1438             {
1439                 if (string.IsNullOrEmpty(userName))
1440                 {
1441                     var target = tab.User;
1442                     if (string.IsNullOrEmpty(target)) return;
1443                     userName = target;
1444                     res = twCon.UserTimeline(null, target, count, null, null, ref content);
1445                 }
1446                 else
1447                 {
1448                     if (more)
1449                     {
1450                         res = twCon.UserTimeline(null, userName, count, tab.OldestId, null, ref content);
1451                     }
1452                     else
1453                     {
1454                         res = twCon.UserTimeline(null, userName, count, null, null, ref content);
1455                     }
1456                 }
1457             }
1458             catch(Exception ex)
1459             {
1460                 throw new WebApiException("Err:" + ex.Message, ex);
1461             }
1462
1463             if (res == HttpStatusCode.Unauthorized)
1464                 throw new WebApiException("Err:@" + userName + "'s Tweets are protected.");
1465
1466             this.CheckStatusCode(res, content);
1467
1468             var minimumId = CreatePostsFromJson(content, MyCommon.WORKERTYPE.UserTimeline, tab, read);
1469
1470             if (minimumId != null)
1471                 tab.OldestId = minimumId.Value;
1472         }
1473
1474         public PostClass GetStatusApi(bool read, long id)
1475         {
1476             this.CheckAccountState();
1477
1478             HttpStatusCode res;
1479             var content = "";
1480             try
1481             {
1482                 res = twCon.ShowStatuses(id, ref content);
1483             }
1484             catch(Exception ex)
1485             {
1486                 throw new WebApiException("Err:" + ex.Message, ex);
1487             }
1488
1489             if (res == HttpStatusCode.Forbidden)
1490                 throw new WebApiException("Err:protected user's tweet", content);
1491
1492             this.CheckStatusCode(res, content);
1493
1494             TwitterStatus status;
1495             try
1496             {
1497                 status = TwitterStatus.ParseJson(content);
1498             }
1499             catch(SerializationException ex)
1500             {
1501                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1502                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1503             }
1504             catch(Exception ex)
1505             {
1506                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1507                 throw new WebApiException("Invalid Json!", content, ex);
1508             }
1509
1510             var item = CreatePostsFromStatusData(status);
1511             if (item == null)
1512                 throw new WebApiException("Err:Can't create post", content);
1513
1514             item.IsRead = read;
1515             if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
1516
1517             return item;
1518         }
1519
1520         public void GetStatusApi(bool read, long id, TabClass tab)
1521         {
1522             var post = this.GetStatusApi(read, id);
1523
1524             //非同期アイコン取得&StatusDictionaryに追加
1525             if (tab != null && tab.IsInnerStorageTabType)
1526                 tab.AddPostToInnerStorage(post);
1527             else
1528                 TabInformations.GetInstance().AddPost(post);
1529         }
1530
1531         private PostClass CreatePostsFromStatusData(TwitterStatus status)
1532         {
1533             return CreatePostsFromStatusData(status, false);
1534         }
1535
1536         private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
1537         {
1538             var post = new PostClass();
1539             TwitterEntities entities;
1540             string sourceHtml;
1541
1542             post.StatusId = status.Id;
1543             if (status.RetweetedStatus != null)
1544             {
1545                 var retweeted = status.RetweetedStatus;
1546
1547                 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
1548
1549                 //Id
1550                 post.RetweetedId = retweeted.Id;
1551                 //本文
1552                 post.TextFromApi = retweeted.Text;
1553                 entities = retweeted.MergedEntities;
1554                 sourceHtml = retweeted.Source;
1555                 //Reply先
1556                 post.InReplyToStatusId = retweeted.InReplyToStatusId;
1557                 post.InReplyToUser = retweeted.InReplyToScreenName;
1558                 post.InReplyToUserId = status.InReplyToUserId;
1559
1560                 if (favTweet)
1561                 {
1562                     post.IsFav = true;
1563                 }
1564                 else
1565                 {
1566                     //幻覚fav対策
1567                     var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1568                     post.IsFav = tc.Contains(retweeted.Id);
1569                 }
1570
1571                 if (retweeted.Coordinates != null)
1572                     post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
1573
1574                 //以下、ユーザー情報
1575                 var user = retweeted.User;
1576
1577                 if (user == null || user.ScreenName == null || status.User.ScreenName == null) return null;
1578
1579                 post.UserId = user.Id;
1580                 post.ScreenName = user.ScreenName;
1581                 post.Nickname = user.Name.Trim();
1582                 post.ImageUrl = user.ProfileImageUrlHttps;
1583                 post.IsProtect = user.Protected;
1584
1585                 //Retweetした人
1586                 post.RetweetedBy = status.User.ScreenName;
1587                 post.RetweetedByUserId = status.User.Id;
1588                 post.IsMe = post.RetweetedBy.ToLower().Equals(_uname);
1589             }
1590             else
1591             {
1592                 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
1593                 //本文
1594                 post.TextFromApi = status.Text;
1595                 entities = status.MergedEntities;
1596                 sourceHtml = status.Source;
1597                 post.InReplyToStatusId = status.InReplyToStatusId;
1598                 post.InReplyToUser = status.InReplyToScreenName;
1599                 post.InReplyToUserId = status.InReplyToUserId;
1600
1601                 if (favTweet)
1602                 {
1603                     post.IsFav = true;
1604                 }
1605                 else
1606                 {
1607                     //幻覚fav対策
1608                     var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1609                     post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
1610                 }
1611
1612                 if (status.Coordinates != null)
1613                     post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
1614
1615                 //以下、ユーザー情報
1616                 var user = status.User;
1617
1618                 if (user == null || user.ScreenName == null) return null;
1619
1620                 post.UserId = user.Id;
1621                 post.ScreenName = user.ScreenName;
1622                 post.Nickname = user.Name.Trim();
1623                 post.ImageUrl = user.ProfileImageUrlHttps;
1624                 post.IsProtect = user.Protected;
1625                 post.IsMe = post.ScreenName.ToLower().Equals(_uname);
1626             }
1627             //HTMLに整形
1628             string textFromApi = post.TextFromApi;
1629             post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
1630             post.TextFromApi = textFromApi;
1631             post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
1632             post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1633             post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1634
1635             post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
1636                 .Where(x => x != post.StatusId && x != post.RetweetedId)
1637                 .Distinct().ToArray();
1638
1639             post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
1640                 .Where(x => x != null)
1641                 .GroupBy(x => x.Url)
1642                 .ToDictionary(x => x.Key, x => new PostClass.ExpandedUrlInfo(x.Key, x.First().ExpandedUrl));
1643
1644             //Source整形
1645             var source = ParseSource(sourceHtml);
1646             post.Source = source.Item1;
1647             post.SourceUri = source.Item2;
1648
1649             post.IsReply = post.ReplyToList.Contains(_uname);
1650             post.IsExcludeReply = false;
1651
1652             if (post.IsMe)
1653             {
1654                 post.IsOwl = false;
1655             }
1656             else
1657             {
1658                 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
1659             }
1660
1661             post.IsDm = false;
1662             return post;
1663         }
1664
1665         /// <summary>
1666         /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
1667         /// </summary>
1668         public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
1669         {
1670             var urls = entities.OfType<TwitterEntityUrl>().Where(x => x != null)
1671                 .Select(x => x.ExpandedUrl);
1672
1673             return GetQuoteTweetStatusIds(urls);
1674         }
1675
1676         public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
1677         {
1678             foreach (var url in urls)
1679             {
1680                 var match = Twitter.StatusUrlRegex.Match(url);
1681                 if (match.Success)
1682                 {
1683                     long statusId;
1684                     if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
1685                         yield return statusId;
1686                 }
1687             }
1688         }
1689
1690         private long? CreatePostsFromJson(string content, MyCommon.WORKERTYPE gType, TabClass tab, bool read)
1691         {
1692             TwitterStatus[] items;
1693             try
1694             {
1695                 items = TwitterStatus.ParseJsonArray(content);
1696             }
1697             catch(SerializationException ex)
1698             {
1699                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1700                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1701             }
1702             catch(Exception ex)
1703             {
1704                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1705                 throw new WebApiException("Invalid Json!", content, ex);
1706             }
1707
1708             long? minimumId = null;
1709
1710             foreach (var status in items)
1711             {
1712                 PostClass post = null;
1713                 post = CreatePostsFromStatusData(status);
1714                 if (post == null) continue;
1715
1716                 if (minimumId == null || minimumId.Value > post.StatusId)
1717                     minimumId = post.StatusId;
1718
1719                 //二重取得回避
1720                 lock (LockObj)
1721                 {
1722                     if (tab == null)
1723                     {
1724                         if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1725                     }
1726                     else
1727                     {
1728                         if (tab.Contains(post.StatusId)) continue;
1729                     }
1730                 }
1731
1732                 //RT禁止ユーザーによるもの
1733                 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
1734                     post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
1735
1736                 post.IsRead = read;
1737                 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1738
1739                 //非同期アイコン取得&StatusDictionaryに追加
1740                 if (tab != null && tab.IsInnerStorageTabType)
1741                     tab.AddPostToInnerStorage(post);
1742                 else
1743                     TabInformations.GetInstance().AddPost(post);
1744             }
1745
1746             return minimumId;
1747         }
1748
1749         private long? CreatePostsFromSearchJson(string content, TabClass tab, bool read, int count, bool more)
1750         {
1751             TwitterSearchResult items;
1752             try
1753             {
1754                 items = TwitterSearchResult.ParseJson(content);
1755             }
1756             catch (SerializationException ex)
1757             {
1758                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1759                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1760             }
1761             catch (Exception ex)
1762             {
1763                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1764                 throw new WebApiException("Invalid Json!", content, ex);
1765             }
1766
1767             long? minimumId = null;
1768
1769             foreach (var result in items.Statuses)
1770             {
1771                 PostClass post = null;
1772                 post = CreatePostsFromStatusData(result);
1773
1774                 if (post == null)
1775                 {
1776                     // Search API は相変わらずぶっ壊れたデータを返すことがあるため、必要なデータが欠如しているものは取得し直す
1777                     try
1778                     {
1779                         post = this.GetStatusApi(read, result.Id);
1780                     }
1781                     catch (WebApiException)
1782                     {
1783                         continue;
1784                     }
1785                 }
1786
1787                 if (minimumId == null || minimumId.Value > post.StatusId)
1788                     minimumId = post.StatusId;
1789
1790                 if (!more && post.StatusId > tab.SinceId) tab.SinceId = post.StatusId;
1791                 //二重取得回避
1792                 lock (LockObj)
1793                 {
1794                     if (tab == null)
1795                     {
1796                         if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1797                     }
1798                     else
1799                     {
1800                         if (tab.Contains(post.StatusId)) continue;
1801                     }
1802                 }
1803
1804                 post.IsRead = read;
1805                 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
1806
1807                 //非同期アイコン取得&StatusDictionaryに追加
1808                 if (tab != null && tab.IsInnerStorageTabType)
1809                     tab.AddPostToInnerStorage(post);
1810                 else
1811                     TabInformations.GetInstance().AddPost(post);
1812             }
1813
1814             return minimumId;
1815         }
1816
1817         private void CreateFavoritePostsFromJson(string content, bool read)
1818         {
1819             TwitterStatus[] item;
1820             try
1821             {
1822                 item = TwitterStatus.ParseJsonArray(content);
1823             }
1824             catch (SerializationException ex)
1825             {
1826                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1827                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1828             }
1829             catch (Exception ex)
1830             {
1831                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1832                 throw new WebApiException("Invalid Json!", content, ex);
1833             }
1834
1835             var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1836
1837             foreach (var status in item)
1838             {
1839                 //二重取得回避
1840                 lock (LockObj)
1841                 {
1842                     if (favTab.Contains(status.Id)) continue;
1843                 }
1844
1845                 var post = CreatePostsFromStatusData(status, true);
1846                 if (post == null) continue;
1847
1848                 post.IsRead = read;
1849
1850                 TabInformations.GetInstance().AddPost(post);
1851             }
1852         }
1853
1854         public void GetListStatus(bool read,
1855                                 TabClass tab,
1856                                 bool more,
1857                                 bool startup)
1858         {
1859             HttpStatusCode res;
1860             var content = "";
1861             var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
1862
1863             try
1864             {
1865                 if (more)
1866                 {
1867                     res = twCon.GetListsStatuses(tab.ListInfo.UserId, tab.ListInfo.Id, count, tab.OldestId, null, SettingCommon.Instance.IsListsIncludeRts, ref content);
1868                 }
1869                 else
1870                 {
1871                     res = twCon.GetListsStatuses(tab.ListInfo.UserId, tab.ListInfo.Id, count, null, null, SettingCommon.Instance.IsListsIncludeRts, ref content);
1872                 }
1873             }
1874             catch(Exception ex)
1875             {
1876                 throw new WebApiException("Err:" + ex.Message, ex);
1877             }
1878
1879             this.CheckStatusCode(res, content);
1880
1881             var minimumId = CreatePostsFromJson(content, MyCommon.WORKERTYPE.List, tab, read);
1882
1883             if (minimumId != null)
1884                 tab.OldestId = minimumId.Value;
1885         }
1886
1887         /// <summary>
1888         /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1889         /// </summary>
1890         /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1891         internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1892         {
1893             if (!posts.ContainsKey(startStatusId))
1894                 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1895
1896             var nextPost = posts[startStatusId];
1897             while (nextPost.InReplyToStatusId != null)
1898             {
1899                 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1900                     break;
1901                 nextPost = posts[nextPost.InReplyToStatusId.Value];
1902             }
1903
1904             return nextPost;
1905         }
1906
1907         public void GetRelatedResult(bool read, TabClass tab)
1908         {
1909             var relPosts = new Dictionary<Int64, PostClass>();
1910             if (tab.RelationTargetPost.TextFromApi.Contains("@") && tab.RelationTargetPost.InReplyToStatusId == null)
1911             {
1912                 //検索結果対応
1913                 var p = TabInformations.GetInstance()[tab.RelationTargetPost.StatusId];
1914                 if (p != null && p.InReplyToStatusId != null)
1915                 {
1916                     tab.RelationTargetPost = p;
1917                 }
1918                 else
1919                 {
1920                     p = this.GetStatusApi(read, tab.RelationTargetPost.StatusId);
1921                     tab.RelationTargetPost = p;
1922                 }
1923             }
1924             relPosts.Add(tab.RelationTargetPost.StatusId, tab.RelationTargetPost);
1925
1926             Exception lastException = null;
1927
1928             // in_reply_to_status_id を使用してリプライチェインを辿る
1929             var nextPost = FindTopOfReplyChain(relPosts, tab.RelationTargetPost.StatusId);
1930             var loopCount = 1;
1931             while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1932             {
1933                 var inReplyToId = nextPost.InReplyToStatusId.Value;
1934
1935                 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1936                 if (inReplyToPost == null)
1937                 {
1938                     try
1939                     {
1940                         inReplyToPost = this.GetStatusApi(read, inReplyToId);
1941                     }
1942                     catch (WebApiException ex)
1943                     {
1944                         lastException = ex;
1945                         break;
1946                     }
1947                 }
1948
1949                 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1950
1951                 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1952             }
1953
1954             //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1955             var text = tab.RelationTargetPost.Text;
1956             var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1957                 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1958             foreach (var _match in ma)
1959             {
1960                 Int64 _statusId;
1961                 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1962                 {
1963                     if (relPosts.ContainsKey(_statusId))
1964                         continue;
1965
1966                     var p = TabInformations.GetInstance()[_statusId];
1967                     if (p == null)
1968                     {
1969                         try
1970                         {
1971                             p = this.GetStatusApi(read, _statusId);
1972                         }
1973                         catch (WebApiException ex)
1974                         {
1975                             lastException = ex;
1976                             break;
1977                         }
1978                     }
1979
1980                     if (p != null)
1981                         relPosts.Add(p.StatusId, p);
1982                 }
1983             }
1984
1985             relPosts.Values.ToList().ForEach(p =>
1986             {
1987                 if (p.IsMe && !read && this._readOwnPost)
1988                     p.IsRead = true;
1989                 else
1990                     p.IsRead = read;
1991
1992                 tab.AddPostToInnerStorage(p);
1993             });
1994
1995             if (lastException != null)
1996                 throw new WebApiException(lastException.Message, lastException);
1997         }
1998
1999         public void GetSearch(bool read,
2000                             TabClass tab,
2001                             bool more)
2002         {
2003             HttpStatusCode res;
2004             var content = "";
2005             var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
2006             long? maxId = null;
2007             long? sinceId = null;
2008             if (more)
2009             {
2010                 maxId = tab.OldestId - 1;
2011             }
2012             else
2013             {
2014                 sinceId = tab.SinceId;
2015             }
2016
2017             try
2018             {
2019                 // TODO:一時的に40>100件に 件数変更UI作成の必要あり
2020                 res = twCon.Search(tab.SearchWords, tab.SearchLang, count, maxId, sinceId, ref content);
2021             }
2022             catch(Exception ex)
2023             {
2024                 throw new WebApiException("Err:" + ex.Message, ex);
2025             }
2026             switch (res)
2027             {
2028                 case HttpStatusCode.BadRequest:
2029                     throw new WebApiException("Invalid query", content);
2030                 case HttpStatusCode.NotFound:
2031                     throw new WebApiException("Invalid query", content);
2032                 case HttpStatusCode.PaymentRequired: //API Documentには420と書いてあるが、該当コードがないので402にしてある
2033                     throw new WebApiException("Search API Limit?", content);
2034                 case HttpStatusCode.OK:
2035                     break;
2036                 default:
2037                     throw new WebApiException("Err:" + res.ToString() + "(" + MethodBase.GetCurrentMethod().Name + ")", content);
2038             }
2039
2040             if (!TabInformations.GetInstance().ContainsTab(tab))
2041                 return;
2042
2043             var minimumId =  this.CreatePostsFromSearchJson(content, tab, read, count, more);
2044
2045             if (minimumId != null)
2046                 tab.OldestId = minimumId.Value;
2047         }
2048
2049         private void CreateDirectMessagesFromJson(string content, MyCommon.WORKERTYPE gType, bool read)
2050         {
2051             TwitterDirectMessage[] item;
2052             try
2053             {
2054                 if (gType == MyCommon.WORKERTYPE.UserStream)
2055                 {
2056                     item = new[] { TwitterStreamEventDirectMessage.ParseJson(content).DirectMessage };
2057                 }
2058                 else
2059                 {
2060                     item = TwitterDirectMessage.ParseJsonArray(content);
2061                 }
2062             }
2063             catch(SerializationException ex)
2064             {
2065                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2066                 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
2067             }
2068             catch(Exception ex)
2069             {
2070                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2071                 throw new WebApiException("Invalid Json!", content, ex);
2072             }
2073
2074             foreach (var message in item)
2075             {
2076                 var post = new PostClass();
2077                 try
2078                 {
2079                     post.StatusId = message.Id;
2080                     if (gType != MyCommon.WORKERTYPE.UserStream)
2081                     {
2082                         if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
2083                         {
2084                             if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
2085                         }
2086                         else
2087                         {
2088                             if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
2089                         }
2090                     }
2091
2092                     //二重取得回避
2093                     lock (LockObj)
2094                     {
2095                         if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
2096                     }
2097                     //sender_id
2098                     //recipient_id
2099                     post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
2100                     //本文
2101                     var textFromApi = message.Text;
2102                     //HTMLに整形
2103                     post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
2104                     post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
2105                     post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
2106                     post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
2107                     post.IsFav = false;
2108
2109                     post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
2110
2111                     post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
2112                         .Where(x => x != null)
2113                         .GroupBy(x => x.Url)
2114                         .ToDictionary(x => x.Key, x => new PostClass.ExpandedUrlInfo(x.Key, x.First().ExpandedUrl));
2115
2116                     //以下、ユーザー情報
2117                     TwitterUser user;
2118                     if (gType == MyCommon.WORKERTYPE.UserStream)
2119                     {
2120                         if (twCon.AuthenticatedUsername.Equals(message.Recipient.ScreenName, StringComparison.CurrentCultureIgnoreCase))
2121                         {
2122                             user = message.Sender;
2123                             post.IsMe = false;
2124                             post.IsOwl = true;
2125                         }
2126                         else
2127                         {
2128                             user = message.Recipient;
2129                             post.IsMe = true;
2130                             post.IsOwl = false;
2131                         }
2132                     }
2133                     else
2134                     {
2135                         if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
2136                         {
2137                             user = message.Sender;
2138                             post.IsMe = false;
2139                             post.IsOwl = true;
2140                         }
2141                         else
2142                         {
2143                             user = message.Recipient;
2144                             post.IsMe = true;
2145                             post.IsOwl = false;
2146                         }
2147                     }
2148
2149                     post.UserId = user.Id;
2150                     post.ScreenName = user.ScreenName;
2151                     post.Nickname = user.Name.Trim();
2152                     post.ImageUrl = user.ProfileImageUrlHttps;
2153                     post.IsProtect = user.Protected;
2154                 }
2155                 catch(Exception ex)
2156                 {
2157                     MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2158                     MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
2159                     continue;
2160                 }
2161
2162                 post.IsRead = read;
2163                 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
2164                 post.IsReply = false;
2165                 post.IsExcludeReply = false;
2166                 post.IsDm = true;
2167
2168                 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
2169                 dmTab.AddPostToInnerStorage(post);
2170             }
2171         }
2172
2173         public void GetDirectMessageApi(bool read,
2174                                 MyCommon.WORKERTYPE gType,
2175                                 bool more)
2176         {
2177             this.CheckAccountState();
2178             this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
2179
2180             HttpStatusCode res;
2181             var content = "";
2182             var count = GetApiResultCount(gType, more, false);
2183
2184             try
2185             {
2186                 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
2187                 {
2188                     if (more)
2189                     {
2190                         res = twCon.DirectMessages(count, minDirectmessage, null, ref content);
2191                     }
2192                     else
2193                     {
2194                         res = twCon.DirectMessages(count, null, null, ref content);
2195                     }
2196                 }
2197                 else
2198                 {
2199                     if (more)
2200                     {
2201                         res = twCon.DirectMessagesSent(count, minDirectmessageSent, null, ref content);
2202                     }
2203                     else
2204                     {
2205                         res = twCon.DirectMessagesSent(count, null, null, ref content);
2206                     }
2207                 }
2208             }
2209             catch(Exception ex)
2210             {
2211                 throw new WebApiException("Err:" + ex.Message, ex);
2212             }
2213
2214             this.CheckStatusCode(res, content);
2215
2216             CreateDirectMessagesFromJson(content, gType, read);
2217         }
2218
2219         public void GetFavoritesApi(bool read,
2220                             bool more)
2221         {
2222             this.CheckAccountState();
2223
2224             HttpStatusCode res;
2225             var content = "";
2226             var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
2227
2228             try
2229             {
2230                 res = twCon.Favorites(count, ref content);
2231             }
2232             catch(Exception ex)
2233             {
2234                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2235             }
2236
2237             this.CheckStatusCode(res, content);
2238
2239             CreateFavoritePostsFromJson(content, read);
2240         }
2241
2242         private string ReplaceTextFromApi(string text, TwitterEntities entities)
2243         {
2244             if (entities != null)
2245             {
2246                 if (entities.Urls != null)
2247                 {
2248                     foreach (var m in entities.Urls)
2249                     {
2250                         if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
2251                     }
2252                 }
2253                 if (entities.Media != null)
2254                 {
2255                     foreach (var m in entities.Media)
2256                     {
2257                         if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
2258                     }
2259                 }
2260             }
2261             return text;
2262         }
2263
2264         /// <summary>
2265         /// フォロワーIDを更新します
2266         /// </summary>
2267         /// <exception cref="WebApiException"/>
2268         public void RefreshFollowerIds()
2269         {
2270             if (MyCommon._endingFlag) return;
2271
2272             var cursor = -1L;
2273             var newFollowerIds = new HashSet<long>();
2274             do
2275             {
2276                 var ret = this.GetFollowerIdsApi(ref cursor);
2277                 newFollowerIds.UnionWith(ret.Ids);
2278                 cursor = ret.NextCursor;
2279             } while (cursor != 0);
2280
2281             this.followerId = newFollowerIds;
2282             TabInformations.GetInstance().RefreshOwl(this.followerId);
2283
2284             this._GetFollowerResult = true;
2285         }
2286
2287         public bool GetFollowersSuccess
2288         {
2289             get
2290             {
2291                 return _GetFollowerResult;
2292             }
2293         }
2294
2295         private TwitterIds GetFollowerIdsApi(ref long cursor)
2296         {
2297             this.CheckAccountState();
2298
2299             HttpStatusCode res;
2300             var content = "";
2301             try
2302             {
2303                 res = twCon.FollowerIds(cursor, ref content);
2304             }
2305             catch(Exception e)
2306             {
2307                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2308             }
2309
2310             this.CheckStatusCode(res, content);
2311
2312             try
2313             {
2314                 var ret = TwitterIds.ParseJson(content);
2315
2316                 if (ret.Ids == null)
2317                 {
2318                     var ex = new WebApiException("Err: ret.id == null (GetFollowerIdsApi)", content);
2319                     MyCommon.ExceptionOut(ex);
2320                     throw ex;
2321                 }
2322
2323                 return ret;
2324             }
2325             catch(SerializationException e)
2326             {
2327                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2328                 MyCommon.TraceOut(ex);
2329                 throw ex;
2330             }
2331             catch(Exception e)
2332             {
2333                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2334                 MyCommon.TraceOut(ex);
2335                 throw ex;
2336             }
2337         }
2338
2339         /// <summary>
2340         /// RT 非表示ユーザーを更新します
2341         /// </summary>
2342         /// <exception cref="WebApiException"/>
2343         public void RefreshNoRetweetIds()
2344         {
2345             if (MyCommon._endingFlag) return;
2346
2347             this.noRTId = this.NoRetweetIdsApi();
2348
2349             this._GetNoRetweetResult = true;
2350         }
2351
2352         private long[] NoRetweetIdsApi()
2353         {
2354             this.CheckAccountState();
2355
2356             HttpStatusCode res;
2357             var content = "";
2358             try
2359             {
2360                 res = twCon.NoRetweetIds(ref content);
2361             }
2362             catch(Exception e)
2363             {
2364                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2365             }
2366
2367             this.CheckStatusCode(res, content);
2368
2369             try
2370             {
2371                 return MyCommon.CreateDataFromJson<long[]>(content);
2372             }
2373             catch(SerializationException e)
2374             {
2375                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2376                 MyCommon.TraceOut(ex);
2377                 throw ex;
2378             }
2379             catch(Exception e)
2380             {
2381                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2382                 MyCommon.TraceOut(ex);
2383                 throw ex;
2384             }
2385         }
2386
2387         public bool GetNoRetweetSuccess
2388         {
2389             get
2390             {
2391                 return _GetNoRetweetResult;
2392             }
2393         }
2394
2395         /// <summary>
2396         /// t.co の文字列長などの設定情報を更新します
2397         /// </summary>
2398         /// <exception cref="WebApiException"/>
2399         public void RefreshConfiguration()
2400         {
2401             this.Configuration = this.ConfigurationApi();
2402         }
2403
2404         private TwitterConfiguration ConfigurationApi()
2405         {
2406             HttpStatusCode res;
2407             var content = "";
2408             try
2409             {
2410                 res = twCon.GetConfiguration(ref content);
2411             }
2412             catch(Exception e)
2413             {
2414                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2415             }
2416
2417             this.CheckStatusCode(res, content);
2418
2419             try
2420             {
2421                 return TwitterConfiguration.ParseJson(content);
2422             }
2423             catch(SerializationException e)
2424             {
2425                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2426                 MyCommon.TraceOut(ex);
2427                 throw ex;
2428             }
2429             catch(Exception e)
2430             {
2431                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2432                 MyCommon.TraceOut(ex);
2433                 throw ex;
2434             }
2435         }
2436
2437         public void GetListsApi()
2438         {
2439             this.CheckAccountState();
2440
2441             HttpStatusCode res;
2442             IEnumerable<ListElement> lists;
2443             var content = "";
2444
2445             try
2446             {
2447                 res = twCon.GetLists(this.Username, ref content);
2448             }
2449             catch (Exception ex)
2450             {
2451                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2452             }
2453
2454             this.CheckStatusCode(res, content);
2455
2456             try
2457             {
2458                 lists = TwitterList.ParseJsonArray(content)
2459                     .Select(x => new ListElement(x, this));
2460             }
2461             catch (SerializationException ex)
2462             {
2463                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2464                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2465             }
2466             catch (Exception ex)
2467             {
2468                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2469                 throw new WebApiException("Err:Invalid Json!", content, ex);
2470             }
2471
2472             try
2473             {
2474                 res = twCon.GetListsSubscriptions(this.Username, ref content);
2475             }
2476             catch (Exception ex)
2477             {
2478                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2479             }
2480
2481             this.CheckStatusCode(res, content);
2482
2483             try
2484             {
2485                 lists = lists.Concat(TwitterList.ParseJsonArray(content)
2486                     .Select(x => new ListElement(x, this)));
2487             }
2488             catch (SerializationException ex)
2489             {
2490                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2491                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2492             }
2493             catch (Exception ex)
2494             {
2495                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2496                 throw new WebApiException("Err:Invalid Json!", content, ex);
2497             }
2498
2499             TabInformations.GetInstance().SubscribableLists = lists.ToList();
2500         }
2501
2502         public void DeleteList(string list_id)
2503         {
2504             HttpStatusCode res;
2505             var content = "";
2506
2507             try
2508             {
2509                 res = twCon.DeleteListID(this.Username, list_id, ref content);
2510             }
2511             catch(Exception ex)
2512             {
2513                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2514             }
2515
2516             this.CheckStatusCode(res, content);
2517         }
2518
2519         public ListElement EditList(string list_id, string new_name, bool isPrivate, string description)
2520         {
2521             HttpStatusCode res;
2522             var content = "";
2523
2524             try
2525             {
2526                 res = twCon.UpdateListID(this.Username, list_id, new_name, isPrivate, description, ref content);
2527             }
2528             catch(Exception ex)
2529             {
2530                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2531             }
2532
2533             this.CheckStatusCode(res, content);
2534
2535             try
2536             {
2537                 var le = TwitterList.ParseJson(content);
2538                 return  new ListElement(le, this);
2539             }
2540             catch(SerializationException ex)
2541             {
2542                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2543                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2544             }
2545             catch(Exception ex)
2546             {
2547                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2548                 throw new WebApiException("Err:Invalid Json!", content, ex);
2549             }
2550         }
2551
2552         public long GetListMembers(string list_id, List<UserInfo> lists, long cursor)
2553         {
2554             this.CheckAccountState();
2555
2556             HttpStatusCode res;
2557             var content = "";
2558             try
2559             {
2560                 res = twCon.GetListMembers(this.Username, list_id, cursor, ref content);
2561             }
2562             catch(Exception ex)
2563             {
2564                 throw new WebApiException("Err:" + ex.Message);
2565             }
2566
2567             this.CheckStatusCode(res, content);
2568
2569             try
2570             {
2571                 var users = TwitterUsers.ParseJson(content);
2572                 Array.ForEach<TwitterUser>(
2573                     users.Users,
2574                     u => lists.Add(new UserInfo(u)));
2575
2576                 return users.NextCursor;
2577             }
2578             catch(SerializationException ex)
2579             {
2580                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2581                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2582             }
2583             catch(Exception ex)
2584             {
2585                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2586                 throw new WebApiException("Err:Invalid Json!", content, ex);
2587             }
2588         }
2589
2590         public void CreateListApi(string listName, bool isPrivate, string description)
2591         {
2592             this.CheckAccountState();
2593
2594             HttpStatusCode res;
2595             var content = "";
2596             try
2597             {
2598                 res = twCon.CreateLists(listName, isPrivate, description, ref content);
2599             }
2600             catch(Exception ex)
2601             {
2602                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2603             }
2604
2605             this.CheckStatusCode(res, content);
2606
2607             try
2608             {
2609                 var le = TwitterList.ParseJson(content);
2610                 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(le, this));
2611             }
2612             catch(SerializationException ex)
2613             {
2614                 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2615                 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2616             }
2617             catch(Exception ex)
2618             {
2619                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2620                 throw new WebApiException("Err:Invalid Json!", content, ex);
2621             }
2622         }
2623
2624         public bool ContainsUserAtList(string listId, string user)
2625         {
2626             this.CheckAccountState();
2627
2628             HttpStatusCode res;
2629             var content = "";
2630
2631             try
2632             {
2633                 res = this.twCon.ShowListMember(listId, user, ref content);
2634             }
2635             catch(Exception ex)
2636             {
2637                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2638             }
2639
2640             if (res == HttpStatusCode.NotFound)
2641             {
2642                 return false;
2643             }
2644
2645             this.CheckStatusCode(res, content);
2646
2647             try
2648             {
2649                 TwitterUser.ParseJson(content);
2650                 return true;
2651             }
2652             catch(Exception)
2653             {
2654                 return false;
2655             }
2656         }
2657
2658         public void AddUserToList(string listId, string user)
2659         {
2660             HttpStatusCode res;
2661             var content = "";
2662
2663             try
2664             {
2665                 res = twCon.CreateListMembers(listId, user, ref content);
2666             }
2667             catch(Exception ex)
2668             {
2669                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2670             }
2671
2672             this.CheckStatusCode(res, content);
2673         }
2674
2675         public void RemoveUserToList(string listId, string user)
2676         {
2677             HttpStatusCode res;
2678             var content = "";
2679
2680             try
2681             {
2682                 res = twCon.DeleteListMembers(listId, user, ref content);
2683             }
2684             catch(Exception ex)
2685             {
2686                 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2687             }
2688
2689             this.CheckStatusCode(res, content);
2690         }
2691
2692         public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
2693         {
2694             if (entities != null)
2695             {
2696                 if (entities.Hashtags != null)
2697                 {
2698                     lock (this.LockObj)
2699                     {
2700                         this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
2701                     }
2702                 }
2703                 if (entities.UserMentions != null)
2704                 {
2705                     foreach (var ent in entities.UserMentions)
2706                     {
2707                         var screenName = ent.ScreenName.ToLower();
2708                         if (!AtList.Contains(screenName))
2709                             AtList.Add(screenName);
2710                     }
2711                 }
2712                 if (entities.Media != null)
2713                 {
2714                     if (media != null)
2715                     {
2716                         foreach (var ent in entities.Media)
2717                         {
2718                             if (!media.Any(x => x.Url == ent.MediaUrl))
2719                             {
2720                                 if (ent.VideoInfo != null &&
2721                                     ent.Type == "animated_gif" || ent.Type == "video")
2722                                 {
2723                                     //var videoUrl = ent.VideoInfo.Variants
2724                                     //    .Where(v => v.ContentType == "video/mp4")
2725                                     //    .OrderByDescending(v => v.Bitrate)
2726                                     //    .Select(v => v.Url).FirstOrDefault();
2727                                     media.Add(new MediaInfo(ent.MediaUrl, ent.ExpandedUrl));
2728                                 }
2729                                 else
2730                                     media.Add(new MediaInfo(ent.MediaUrl));
2731                             }
2732                         }
2733                     }
2734                 }
2735             }
2736
2737             // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
2738             text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
2739
2740             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>");
2741             text = PreProcessUrl(text); //IDN置換
2742
2743             return text;
2744         }
2745
2746         /// <summary>
2747         /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
2748         /// </summary>
2749         public static Tuple<string, Uri> ParseSource(string sourceHtml)
2750         {
2751             if (string.IsNullOrEmpty(sourceHtml))
2752                 return Tuple.Create<string, Uri>("", null);
2753
2754             string sourceText;
2755             Uri sourceUri;
2756
2757             // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
2758
2759             var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
2760             if (match.Success)
2761             {
2762                 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
2763                 try
2764                 {
2765                     var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
2766                     sourceUri = new Uri(new Uri("https://twitter.com/"), uriStr);
2767                 }
2768                 catch (UriFormatException)
2769                 {
2770                     sourceUri = null;
2771                 }
2772             }
2773             else
2774             {
2775                 sourceText = WebUtility.HtmlDecode(sourceHtml);
2776                 sourceUri = null;
2777             }
2778
2779             return Tuple.Create(sourceText, sourceUri);
2780         }
2781
2782         public TwitterApiStatus GetInfoApi()
2783         {
2784             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
2785
2786             if (MyCommon._endingFlag) return null;
2787
2788             HttpStatusCode res;
2789             var content = "";
2790             try
2791             {
2792                 res = twCon.RateLimitStatus(ref content);
2793             }
2794             catch (Exception)
2795             {
2796                 this.ResetApiStatus();
2797                 return null;
2798             }
2799
2800             this.CheckStatusCode(res, content);
2801
2802             try
2803             {
2804                 MyCommon.TwitterApiInfo.UpdateFromJson(content);
2805                 return MyCommon.TwitterApiInfo;
2806             }
2807             catch (Exception ex)
2808             {
2809                 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2810                 MyCommon.TwitterApiInfo.Reset();
2811                 return null;
2812             }
2813         }
2814
2815         /// <summary>
2816         /// ブロック中のユーザーを更新します
2817         /// </summary>
2818         /// <exception cref="WebApiException"/>
2819         public void RefreshBlockIds()
2820         {
2821             if (MyCommon._endingFlag) return;
2822
2823             var cursor = -1L;
2824             var newBlockIds = new HashSet<long>();
2825             do
2826             {
2827                 var ret = this.GetBlockIdsApi(cursor);
2828                 newBlockIds.UnionWith(ret.Ids);
2829                 cursor = ret.NextCursor;
2830             } while (cursor != 0);
2831
2832             newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
2833
2834             TabInformations.GetInstance().BlockIds = newBlockIds;
2835         }
2836
2837         public TwitterIds GetBlockIdsApi(long cursor)
2838         {
2839             this.CheckAccountState();
2840
2841             HttpStatusCode res;
2842             var content = "";
2843             try
2844             {
2845                 res = twCon.GetBlockUserIds(ref content, cursor);
2846             }
2847             catch(Exception e)
2848             {
2849                 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2850             }
2851
2852             this.CheckStatusCode(res, content);
2853
2854             try
2855             {
2856                 return TwitterIds.ParseJson(content);
2857             }
2858             catch(SerializationException e)
2859             {
2860                 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2861                 MyCommon.TraceOut(ex);
2862                 throw ex;
2863             }
2864             catch(Exception e)
2865             {
2866                 var ex = new WebApiException("Err:Invalid Json!", content, e);
2867                 MyCommon.TraceOut(ex);
2868                 throw ex;
2869             }
2870         }
2871
2872         /// <summary>
2873         /// ミュート中のユーザーIDを更新します
2874         /// </summary>
2875         /// <exception cref="WebApiException"/>
2876         public async Task RefreshMuteUserIdsAsync()
2877         {
2878             if (MyCommon._endingFlag) return;
2879
2880             var ids = await TwitterIds.GetAllItemsAsync(this.GetMuteUserIdsApiAsync)
2881                 .ConfigureAwait(false);
2882
2883             TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
2884         }
2885
2886         public async Task<TwitterIds> GetMuteUserIdsApiAsync(long cursor)
2887         {
2888             var content = "";
2889
2890             try
2891             {
2892                 var res = await Task.Run(() => twCon.GetMuteUserIds(ref content, cursor))
2893                     .ConfigureAwait(false);
2894
2895                 this.CheckStatusCode(res, content);
2896
2897                 return TwitterIds.ParseJson(content);
2898             }
2899             catch (WebException ex)
2900             {
2901                 var ex2 = new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", content, ex);
2902                 MyCommon.TraceOut(ex2);
2903                 throw ex2;
2904             }
2905             catch (SerializationException ex)
2906             {
2907                 var ex2 = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2908                 MyCommon.TraceOut(ex2);
2909                 throw ex2;
2910             }
2911         }
2912
2913         public string[] GetHashList()
2914         {
2915             string[] hashArray;
2916             lock (LockObj)
2917             {
2918                 hashArray = _hashList.ToArray();
2919                 _hashList.Clear();
2920             }
2921             return hashArray;
2922         }
2923
2924         public string AccessToken
2925         {
2926             get
2927             {
2928                 return twCon.AccessToken;
2929             }
2930         }
2931
2932         public string AccessTokenSecret
2933         {
2934             get
2935             {
2936                 return twCon.AccessTokenSecret;
2937             }
2938         }
2939
2940         private void CheckAccountState()
2941         {
2942             if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2943                 throw new WebApiException("Auth error. Check your account");
2944         }
2945
2946         private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
2947         {
2948             if (!this.AccessLevel.HasFlag(accessLevelFlags))
2949                 throw new WebApiException("Auth Err:try to re-authorization.");
2950         }
2951
2952         private void CheckStatusCode(HttpStatusCode httpStatus, string responseText,
2953             [CallerMemberName] string callerMethodName = "")
2954         {
2955             if (httpStatus == HttpStatusCode.OK)
2956             {
2957                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2958                 return;
2959             }
2960
2961             if (string.IsNullOrWhiteSpace(responseText))
2962             {
2963                 if (httpStatus == HttpStatusCode.Unauthorized)
2964                     Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2965
2966                 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")");
2967             }
2968
2969             try
2970             {
2971                 var errors = TwitterError.ParseJson(responseText).Errors;
2972                 if (errors == null || !errors.Any())
2973                 {
2974                     throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2975                 }
2976
2977                 foreach (var error in errors)
2978                 {
2979                     if (error.Code == TwitterErrorCode.InvalidToken ||
2980                         error.Code == TwitterErrorCode.SuspendedAccount)
2981                     {
2982                         Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2983                     }
2984                 }
2985
2986                 throw new WebApiException("Err:" + string.Join(",", errors.Select(x => x.ToString())) + "(" + callerMethodName + ")", responseText);
2987             }
2988             catch (SerializationException) { }
2989
2990             throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2991         }
2992
2993         public int GetTextLengthRemain(string postText)
2994         {
2995             var matchDm = Twitter.DMSendTextRegex.Match(postText);
2996             if (matchDm.Success)
2997                 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
2998
2999             return this.GetTextLengthRemainInternal(postText, isDm: false);
3000         }
3001
3002         private int GetTextLengthRemainInternal(string postText, bool isDm)
3003         {
3004             var textLength = 0;
3005
3006             var pos = 0;
3007             while (pos < postText.Length)
3008             {
3009                 textLength++;
3010
3011                 if (char.IsSurrogatePair(postText, pos))
3012                     pos += 2; // サロゲートペアの場合は2文字分進める
3013                 else
3014                     pos++;
3015             }
3016
3017             var urls = TweetExtractor.ExtractUrls(postText);
3018             foreach (var url in urls)
3019             {
3020                 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
3021                     ? this.Configuration.ShortUrlLengthHttps
3022                     : this.Configuration.ShortUrlLength;
3023
3024                 textLength += shortUrlLength - url.Length;
3025             }
3026
3027             if (isDm)
3028                 return this.Configuration.DmTextCharacterLimit - textLength;
3029             else
3030                 return 140 - textLength;
3031         }
3032
3033
3034 #region "UserStream"
3035         private string trackWord_ = "";
3036         public string TrackWord
3037         {
3038             get
3039             {
3040                 return trackWord_;
3041             }
3042             set
3043             {
3044                 trackWord_ = value;
3045             }
3046         }
3047         private bool allAtReply_ = false;
3048         public bool AllAtReply
3049         {
3050             get
3051             {
3052                 return allAtReply_;
3053             }
3054             set
3055             {
3056                 allAtReply_ = value;
3057             }
3058         }
3059
3060         public event EventHandler NewPostFromStream;
3061         public event EventHandler UserStreamStarted;
3062         public event EventHandler UserStreamStopped;
3063         public event EventHandler<PostDeletedEventArgs> PostDeleted;
3064         public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
3065         private DateTime _lastUserstreamDataReceived;
3066         private TwitterUserstream userStream;
3067
3068         public class FormattedEvent
3069         {
3070             public MyCommon.EVENTTYPE Eventtype { get; set; }
3071             public DateTime CreatedAt { get; set; }
3072             public string Event { get; set; }
3073             public string Username { get; set; }
3074             public string Target { get; set; }
3075             public Int64 Id { get; set; }
3076             public bool IsMe { get; set; }
3077         }
3078
3079         public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
3080         public List<FormattedEvent> StoredEvent
3081         {
3082             get
3083             {
3084                 return storedEvent_;
3085             }
3086             set
3087             {
3088                 storedEvent_ = value;
3089             }
3090         }
3091
3092         private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
3093         {
3094             ["favorite"] = MyCommon.EVENTTYPE.Favorite,
3095             ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
3096             ["follow"] = MyCommon.EVENTTYPE.Follow,
3097             ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
3098             ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
3099             ["block"] = MyCommon.EVENTTYPE.Block,
3100             ["unblock"] = MyCommon.EVENTTYPE.Unblock,
3101             ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
3102             ["deleted"] = MyCommon.EVENTTYPE.Deleted,
3103             ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
3104             ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
3105             ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
3106             ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
3107             ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
3108             ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
3109             ["mute"] = MyCommon.EVENTTYPE.Mute,
3110             ["unmute"] = MyCommon.EVENTTYPE.Unmute,
3111             ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
3112         };
3113
3114         public bool IsUserstreamDataReceived
3115         {
3116             get
3117             {
3118                 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
3119             }
3120         }
3121
3122         private void userStream_StatusArrived(string line)
3123         {
3124             this._lastUserstreamDataReceived = DateTime.Now;
3125             if (string.IsNullOrEmpty(line)) return;
3126
3127             if (line.First() != '{' || line.Last() != '}')
3128             {
3129                 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
3130                 return;
3131             }
3132
3133             var isDm = false;
3134
3135             try
3136             {
3137                 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
3138                 {
3139                     var xElm = XElement.Load(jsonReader);
3140                     if (xElm.Element("friends") != null)
3141                     {
3142                         Debug.WriteLine("friends");
3143                         return;
3144                     }
3145                     else if (xElm.Element("delete") != null)
3146                     {
3147                         Debug.WriteLine("delete");
3148                         Int64 id;
3149                         XElement idElm;
3150                         if ((idElm = xElm.Element("delete").Element("direct_message")?.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 if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
3158                         {
3159                             id = 0;
3160                             long.TryParse(idElm.Value, out id);
3161
3162                             this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
3163                         }
3164                         else
3165                         {
3166                             MyCommon.TraceOut("delete:" + line);
3167                             return;
3168                         }
3169                         for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
3170                         {
3171                             var sEvt = this.StoredEvent[i];
3172                             if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
3173                             {
3174                                 this.StoredEvent.RemoveAt(i);
3175                             }
3176                         }
3177                         return;
3178                     }
3179                     else if (xElm.Element("limit") != null)
3180                     {
3181                         Debug.WriteLine(line);
3182                         return;
3183                     }
3184                     else if (xElm.Element("event") != null)
3185                     {
3186                         Debug.WriteLine("event: " + xElm.Element("event").Value);
3187                         CreateEventFromJson(line);
3188                         return;
3189                     }
3190                     else if (xElm.Element("direct_message") != null)
3191                     {
3192                         Debug.WriteLine("direct_message");
3193                         isDm = true;
3194                     }
3195                     else if (xElm.Element("retweeted_status") != null)
3196                     {
3197                         var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
3198                         var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
3199
3200                         // 自分に関係しないリツイートの場合は無視する
3201                         var selfUserId = this.UserId.ToString();
3202                         if (sourceUserId == selfUserId || targetUserId == selfUserId)
3203                         {
3204                             // 公式 RT をイベントとしても扱う
3205                             var evt = CreateEventFromRetweet(xElm);
3206                             if (evt != null)
3207                             {
3208                                 this.StoredEvent.Insert(0, evt);
3209
3210                                 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
3211                             }
3212                         }
3213
3214                         // 従来通り公式 RT の表示も行うため return しない
3215                     }
3216                     else if (xElm.Element("scrub_geo") != null)
3217                     {
3218                         try
3219                         {
3220                             TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
3221                                                                         long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
3222                         }
3223                         catch(Exception)
3224                         {
3225                             MyCommon.TraceOut("scrub_geo:" + line);
3226                         }
3227                         return;
3228                     }
3229                 }
3230
3231                 if (isDm)
3232                 {
3233                     CreateDirectMessagesFromJson(line, MyCommon.WORKERTYPE.UserStream, false);
3234                 }
3235                 else
3236                 {
3237                     CreatePostsFromJson("[" + line + "]", MyCommon.WORKERTYPE.Timeline, null, false);
3238                 }
3239             }
3240             catch (WebApiException ex)
3241             {
3242                 MyCommon.TraceOut(ex);
3243                 return;
3244             }
3245             catch(NullReferenceException)
3246             {
3247                 MyCommon.TraceOut("NullRef StatusArrived: " + line);
3248             }
3249
3250             this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
3251         }
3252
3253         /// <summary>
3254         /// UserStreamsから受信した公式RTをイベントに変換します
3255         /// </summary>
3256         private FormattedEvent CreateEventFromRetweet(XElement xElm)
3257         {
3258             return new FormattedEvent
3259             {
3260                 Eventtype = MyCommon.EVENTTYPE.Retweet,
3261                 Event = "retweet",
3262                 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
3263                 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
3264                 Username = xElm.XPathSelectElement("/user/screen_name").Value,
3265                 Target = string.Format("@{0}:{1}", new[]
3266                 {
3267                     xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
3268                     WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
3269                 }),
3270                 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
3271             };
3272         }
3273
3274         private void CreateEventFromJson(string content)
3275         {
3276             TwitterStreamEvent eventData = null;
3277             try
3278             {
3279                 eventData = TwitterStreamEvent.ParseJson(content);
3280             }
3281             catch(SerializationException ex)
3282             {
3283                 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
3284             }
3285             catch(Exception ex)
3286             {
3287                 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
3288             }
3289
3290             var evt = new FormattedEvent();
3291             evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
3292             evt.Event = eventData.Event;
3293             evt.Username = eventData.Source.ScreenName;
3294             evt.IsMe = evt.Username.ToLower().Equals(this.Username.ToLower());
3295
3296             MyCommon.EVENTTYPE eventType;
3297             eventTable.TryGetValue(eventData.Event, out eventType);
3298             evt.Eventtype = eventType;
3299
3300             TwitterStreamEvent<TwitterStatus> tweetEvent;
3301
3302             switch (eventData.Event)
3303             {
3304                 case "access_revoked":
3305                 case "access_unrevoked":
3306                 case "user_delete":
3307                 case "user_suspend":
3308                     return;
3309                 case "follow":
3310                     if (eventData.Target.ScreenName.ToLower().Equals(_uname))
3311                     {
3312                         if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
3313                     }
3314                     else
3315                     {
3316                         return;    //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
3317                     }
3318                     evt.Target = "";
3319                     break;
3320                 case "unfollow":
3321                     evt.Target = "@" + eventData.Target.ScreenName;
3322                     break;
3323                 case "favorited_retweet":
3324                 case "retweeted_retweet":
3325                     return;
3326                 case "favorite":
3327                 case "unfavorite":
3328                     tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
3329                     evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
3330                     evt.Id = tweetEvent.TargetObject.Id;
3331
3332                     if (SettingCommon.Instance.IsRemoveSameEvent)
3333                     {
3334                         if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
3335                             return;
3336                     }
3337
3338                     var tabinfo = TabInformations.GetInstance();
3339
3340                     PostClass post;
3341                     var statusId = tweetEvent.TargetObject.Id;
3342                     if (!tabinfo.Posts.TryGetValue(statusId, out post))
3343                         break;
3344
3345                     if (eventData.Event == "favorite")
3346                     {
3347                         var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
3348                         if (!favTab.Contains(post.StatusId))
3349                             favTab.AddPostImmediately(post.StatusId, post.IsRead);
3350
3351                         if (tweetEvent.Source.Id == this.UserId)
3352                         {
3353                             post.IsFav = true;
3354                         }
3355                         else if (tweetEvent.Target.Id == this.UserId)
3356                         {
3357                             post.FavoritedCount++;
3358
3359                             if (SettingCommon.Instance.FavEventUnread)
3360                                 tabinfo.SetReadAllTab(post.StatusId, read: false);
3361                         }
3362                     }
3363                     else // unfavorite
3364                     {
3365                         if (tweetEvent.Source.Id == this.UserId)
3366                         {
3367                             post.IsFav = false;
3368                         }
3369                         else if (tweetEvent.Target.Id == this.UserId)
3370                         {
3371                             post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
3372                         }
3373                     }
3374                     break;
3375                 case "quoted_tweet":
3376                     if (evt.IsMe) return;
3377
3378                     tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
3379                     evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
3380                     evt.Id = tweetEvent.TargetObject.Id;
3381
3382                     if (SettingCommon.Instance.IsRemoveSameEvent)
3383                     {
3384                         if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
3385                             return;
3386                     }
3387                     break;
3388                 case "list_member_added":
3389                 case "list_member_removed":
3390                 case "list_created":
3391                 case "list_destroyed":
3392                 case "list_updated":
3393                 case "list_user_subscribed":
3394                 case "list_user_unsubscribed":
3395                     var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
3396                     evt.Target = listEvent.TargetObject.FullName;
3397                     break;
3398                 case "block":
3399                     if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
3400                     evt.Target = "";
3401                     break;
3402                 case "unblock":
3403                     if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
3404                     evt.Target = "";
3405                     break;
3406                 case "user_update":
3407                     evt.Target = "";
3408                     break;
3409                 
3410                 // Mute / Unmute
3411                 case "mute":
3412                     evt.Target = "@" + eventData.Target.ScreenName;
3413                     if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
3414                     {
3415                         TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
3416                     }
3417                     break;
3418                 case "unmute":
3419                     evt.Target = "@" + eventData.Target.ScreenName;
3420                     if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
3421                     {
3422                         TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
3423                     }
3424                     break;
3425
3426                 default:
3427                     MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
3428                     break;
3429             }
3430             this.StoredEvent.Insert(0, evt);
3431
3432             this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
3433         }
3434
3435         private void userStream_Started()
3436         {
3437             this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
3438         }
3439
3440         private void userStream_Stopped()
3441         {
3442             this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
3443         }
3444
3445         public bool UserStreamEnabled
3446         {
3447             get
3448             {
3449                 return userStream == null ? false : userStream.Enabled;
3450             }
3451         }
3452
3453         public void StartUserStream()
3454         {
3455             if (userStream != null)
3456             {
3457                 StopUserStream();
3458             }
3459             userStream = new TwitterUserstream(twCon);
3460             userStream.StatusArrived += userStream_StatusArrived;
3461             userStream.Started += userStream_Started;
3462             userStream.Stopped += userStream_Stopped;
3463             userStream.Start(this.AllAtReply, this.TrackWord);
3464         }
3465
3466         public void StopUserStream()
3467         {
3468             userStream?.Dispose();
3469             userStream = null;
3470             if (!MyCommon._endingFlag)
3471             {
3472                 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
3473             }
3474         }
3475
3476         public void ReconnectUserStream()
3477         {
3478             if (userStream != null)
3479             {
3480                 this.StartUserStream();
3481             }
3482         }
3483
3484         private class TwitterUserstream : IDisposable
3485         {
3486             public event Action<string> StatusArrived;
3487             public event Action Stopped;
3488             public event Action Started;
3489             private HttpTwitter twCon;
3490
3491             private Thread _streamThread;
3492             private bool _streamActive;
3493
3494             private bool _allAtreplies = false;
3495             private string _trackwords = "";
3496
3497             public TwitterUserstream(HttpTwitter twitterConnection)
3498             {
3499                 twCon = (HttpTwitter)twitterConnection.Clone();
3500             }
3501
3502             public void Start(bool allAtReplies, string trackwords)
3503             {
3504                 this.AllAtReplies = allAtReplies;
3505                 this.TrackWords = trackwords;
3506                 _streamActive = true;
3507                 if (_streamThread != null && _streamThread.IsAlive) return;
3508                 _streamThread = new Thread(UserStreamLoop);
3509                 _streamThread.Name = "UserStreamReceiver";
3510                 _streamThread.IsBackground = true;
3511                 _streamThread.Start();
3512             }
3513
3514             public bool Enabled
3515             {
3516                 get
3517                 {
3518                     return _streamActive;
3519                 }
3520             }
3521
3522             public bool AllAtReplies
3523             {
3524                 get
3525                 {
3526                     return _allAtreplies;
3527                 }
3528                 set
3529                 {
3530                     _allAtreplies = value;
3531                 }
3532             }
3533
3534             public string TrackWords
3535             {
3536                 get
3537                 {
3538                     return _trackwords;
3539                 }
3540                 set
3541                 {
3542                     _trackwords = value;
3543                 }
3544             }
3545
3546             private void UserStreamLoop()
3547             {
3548                 var sleepSec = 0;
3549                 do
3550                 {
3551                     Stream st = null;
3552                     StreamReader sr = null;
3553                     try
3554                     {
3555                         if (!MyCommon.IsNetworkAvailable())
3556                         {
3557                             sleepSec = 30;
3558                             continue;
3559                         }
3560
3561                         Started?.Invoke();
3562
3563                         var res = twCon.UserStream(ref st, _allAtreplies, _trackwords, Networking.GetUserAgentString());
3564
3565                         switch (res)
3566                         {
3567                             case HttpStatusCode.OK:
3568                                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3569                                 break;
3570                             case HttpStatusCode.Unauthorized:
3571                                 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
3572                                 sleepSec = 120;
3573                                 continue;
3574                         }
3575
3576                         if (st == null)
3577                         {
3578                             sleepSec = 30;
3579                             //MyCommon.TraceOut("Stop:stream is null")
3580                             continue;
3581                         }
3582
3583                         sr = new StreamReader(st);
3584
3585                         while (_streamActive && !sr.EndOfStream && Twitter.AccountState == MyCommon.ACCOUNT_STATE.Valid)
3586                         {
3587                             StatusArrived?.Invoke(sr.ReadLine());
3588                             //this.LastTime = Now;
3589                         }
3590
3591                         if (sr.EndOfStream || Twitter.AccountState == MyCommon.ACCOUNT_STATE.Invalid)
3592                         {
3593                             sleepSec = 30;
3594                             //MyCommon.TraceOut("Stop:EndOfStream")
3595                             continue;
3596                         }
3597                         break;
3598                     }
3599                     catch(WebException ex)
3600                     {
3601                         if (ex.Status == WebExceptionStatus.Timeout)
3602                         {
3603                             sleepSec = 30;                        //MyCommon.TraceOut("Stop:Timeout")
3604                         }
3605                         else if (ex.Response != null && (int)((HttpWebResponse)ex.Response).StatusCode == 420)
3606                         {
3607                             //MyCommon.TraceOut("Stop:Connection Limit")
3608                             break;
3609                         }
3610                         else
3611                         {
3612                             sleepSec = 30;
3613                             //MyCommon.TraceOut("Stop:WebException " + ex.Status.ToString())
3614                         }
3615                     }
3616                     catch(ThreadAbortException)
3617                     {
3618                         break;
3619                     }
3620                     catch(IOException)
3621                     {
3622                         sleepSec = 30;
3623                         //MyCommon.TraceOut("Stop:IOException with Active." + Environment.NewLine + ex.Message)
3624                     }
3625                     catch(ArgumentException ex)
3626                     {
3627                         //System.ArgumentException: ストリームを読み取れませんでした。
3628                         //サーバー側もしくは通信経路上で切断された場合?タイムアウト頻発後発生
3629                         sleepSec = 30;
3630                         MyCommon.TraceOut(ex, "Stop:ArgumentException");
3631                     }
3632                     catch(Exception ex)
3633                     {
3634                         MyCommon.TraceOut("Stop:Exception." + Environment.NewLine + ex.Message);
3635                         MyCommon.ExceptionOut(ex);
3636                         sleepSec = 30;
3637                     }
3638                     finally
3639                     {
3640                         if (_streamActive)
3641                         {
3642                             Stopped?.Invoke();
3643                         }
3644                         twCon.RequestAbort();
3645                         sr?.Close();
3646                         if (sleepSec > 0)
3647                         {
3648                             var ms = 0;
3649                             while (_streamActive && ms < sleepSec * 1000)
3650                             {
3651                                 Thread.Sleep(500);
3652                                 ms += 500;
3653                             }
3654                         }
3655                         sleepSec = 0;
3656                     }
3657                 } while (this._streamActive);
3658
3659                 if (_streamActive)
3660                 {
3661                     Stopped?.Invoke();
3662                 }
3663                 MyCommon.TraceOut("Stop:EndLoop");
3664             }
3665
3666 #region "IDisposable Support"
3667             private bool disposedValue; // 重複する呼び出しを検出するには
3668
3669             // IDisposable
3670             protected virtual void Dispose(bool disposing)
3671             {
3672                 if (!this.disposedValue)
3673                 {
3674                     if (disposing)
3675                     {
3676                         _streamActive = false;
3677                         if (_streamThread != null && _streamThread.IsAlive)
3678                         {
3679                             _streamThread.Abort();
3680                         }
3681                     }
3682                 }
3683                 this.disposedValue = true;
3684             }
3685
3686             //protected Overrides void Finalize()
3687             //{
3688             //    // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3689             //    Dispose(false)
3690             //    MyBase.Finalize()
3691             //}
3692
3693             // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
3694             public void Dispose()
3695             {
3696                 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3697                 Dispose(true);
3698                 GC.SuppressFinalize(this);
3699             }
3700 #endregion
3701
3702         }
3703 #endregion
3704
3705 #region "IDisposable Support"
3706         private bool disposedValue; // 重複する呼び出しを検出するには
3707
3708         // IDisposable
3709         protected virtual void Dispose(bool disposing)
3710         {
3711             if (!this.disposedValue)
3712             {
3713                 if (disposing)
3714                 {
3715                     this.StopUserStream();
3716                 }
3717             }
3718             this.disposedValue = true;
3719         }
3720
3721         //protected Overrides void Finalize()
3722         //{
3723         //    // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3724         //    Dispose(false)
3725         //    MyBase.Finalize()
3726         //}
3727
3728         // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
3729         public void Dispose()
3730         {
3731             // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3732             Dispose(true);
3733             GC.SuppressFinalize(this);
3734         }
3735 #endregion
3736     }
3737
3738     public class PostDeletedEventArgs : EventArgs
3739     {
3740         public long StatusId { get; }
3741
3742         public PostDeletedEventArgs(long statusId)
3743         {
3744             this.StatusId = statusId;
3745         }
3746     }
3747
3748     public class UserStreamEventReceivedEventArgs : EventArgs
3749     {
3750         public Twitter.FormattedEvent EventData { get; }
3751
3752         public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
3753         {
3754             this.EventData = eventData;
3755         }
3756     }
3757 }