OSDN Git Service

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