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.
11 // This file is part of OpenTween.
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)
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
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.
28 using System.Diagnostics;
32 using System.Runtime.CompilerServices;
33 using System.Runtime.Serialization;
34 using System.Runtime.Serialization.Json;
36 using System.Text.RegularExpressions;
37 using System.Threading;
38 using System.Threading.Tasks;
41 using System.Xml.Linq;
42 using System.Xml.XPath;
44 using System.Reflection;
45 using System.Collections.Generic;
47 using System.Windows.Forms;
49 using OpenTween.Api.DataModel;
50 using OpenTween.Connection;
54 public class Twitter : IDisposable
56 #region Regexp from twitter-text-js
58 // The code in this region code block incorporates works covered by
59 // the following copyright and permission notices:
61 // Copyright 2011 Twitter, Inc.
63 // Licensed under the Apache License, Version 2.0 (the "License"); you
64 // may not use this work except in compliance with the License. You
65 // may obtain a copy of the License in the LICENSE file, or at:
67 // http://www.apache.org/licenses/LICENSE-2.0
69 // Unless required by applicable law or agreed to in writing, software
70 // distributed under the License is distributed on an "AS IS" BASIS,
71 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
72 // implied. See the License for the specific language governing
73 // permissions and limitations under the License.
76 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";
77 private const string NON_LATIN_HASHTAG_CHARS = @"\u0400-\u04ff\u0500-\u0527\u1100-\u11ff\u3130-\u3185\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF";
78 //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";
79 private const string CJ_HASHTAG_CHARACTERS = @"\u30A1-\u30FA\u30FC\u3005\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u309A\u3400-\u4DBF\p{IsCJKUnifiedIdeographs}";
80 private const string HASHTAG_BOUNDARY = @"^|$|\s|「|」|。|\.|!";
81 private const string HASHTAG_ALPHA = "[a-z_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
82 private const string HASHTAG_ALPHANUMERIC = "[a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
83 private const string HASHTAG_TERMINATOR = "[^a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
84 public const string HASHTAG = "(" + HASHTAG_BOUNDARY + ")(#|#)(" + HASHTAG_ALPHANUMERIC + "*" + HASHTAG_ALPHA + HASHTAG_ALPHANUMERIC + "*)(?=" + HASHTAG_TERMINATOR + "|" + HASHTAG_BOUNDARY + ")";
86 private const string url_valid_preceding_chars = @"(?:[^A-Za-z0-9@@$##\ufffe\ufeff\uffff\u202a-\u202e]|^)";
87 public const string url_invalid_without_protocol_preceding_chars = @"[-_./]$";
88 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";
89 private const string url_valid_domain_chars = @"[^" + url_invalid_domain_chars + "]";
90 private const string url_valid_subdomain = @"(?:(?:" + url_valid_domain_chars + @"(?:[_-]|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
91 private const string url_valid_domain_name = @"(?:(?:" + url_valid_domain_chars + @"(?:-|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
92 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]|$))";
93 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]|$))";
94 private const string url_valid_punycode = @"(?:xn--[0-9a-z]+)";
95 private const string url_valid_domain = @"(?<domain>" + url_valid_subdomain + "*" + url_valid_domain_name + "(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + ")|" + url_valid_punycode + ")";
96 public const string url_valid_ascii_domain = @"(?:(?:[a-z0-9" + LATIN_ACCENTS + @"]+)\.)+(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + "|" + url_valid_punycode + ")";
97 public const string url_invalid_short_domain = "^" + url_valid_domain_name + url_valid_CCTLD + "$";
98 private const string url_valid_port_number = @"[0-9]+";
100 private const string url_valid_general_path_chars = @"[a-z0-9!*';:=+,.$/%#\[\]\-_~|&" + LATIN_ACCENTS + "]";
101 private const string url_balance_parens = @"(?:\(" + url_valid_general_path_chars + @"+\))";
102 private const string url_valid_path_ending_chars = @"(?:[+\-a-z0-9=_#/" + LATIN_ACCENTS + "]|" + url_balance_parens + ")";
103 private const string pth = "(?:" +
105 url_valid_general_path_chars + "*" +
106 "(?:" + url_balance_parens + url_valid_general_path_chars + "*)*" +
107 url_valid_path_ending_chars +
108 ")|(?:@" + url_valid_general_path_chars + "+/)" +
110 private const string qry = @"(?<query>\?[a-z0-9!?*'();:&=+$/%#\[\]\-_.,~|]*[a-z0-9_&=#/])?";
111 public const string rgUrl = @"(?<before>" + url_valid_preceding_chars + ")" +
112 "(?<url>(?<protocol>https?://)?" +
113 "(?<domain>" + url_valid_domain + ")" +
114 "(?::" + url_valid_port_number + ")?" +
115 "(?<path>/" + pth + "*)?" +
122 /// Twitter API のステータスページのURL
124 public const string ServiceAvailabilityStatusUrl = "https://status.io.watchmouse.com/7617";
127 /// ツイートへのパーマリンクURLを判定する正規表現
129 public static readonly Regex StatusUrlRegex = new Regex(@"https?://([^.]+\.)?twitter\.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)/status(es)?/(?<StatusId>[0-9]+)(/photo)?", RegexOptions.IgnoreCase);
132 /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
134 public static readonly Regex ThirdPartyStatusUrlRegex = new Regex(@"https?://(?:[^.]+\.)?(?:
135 favstar\.fm/users/[a-zA-Z0-9_]+/status/ # Favstar
136 | favstar\.fm/t/ # Favstar (short)
137 | aclog\.koba789\.com/i/ # aclog
138 | frtrt\.net/solo_status\.php\?status= # RtRT
139 )(?<StatusId>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
142 /// DM送信かどうかを判定する正規表現
144 public static readonly Regex DMSendTextRegex = new Regex(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
146 public TwitterConfiguration Configuration { get; private set; }
148 delegate void GetIconImageDelegate(PostClass post);
149 private readonly object LockObj = new object();
150 private ISet<long> followerId = new HashSet<long>();
151 private bool _GetFollowerResult = false;
152 private long[] noRTId = new long[0];
153 private bool _GetNoRetweetResult = false;
156 private string _uname;
158 private bool _readOwnPost;
159 private List<string> _hashList = new List<string>();
161 //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
162 private long minHomeTimeline = long.MaxValue;
163 private long minMentions = long.MaxValue;
164 private long minDirectmessage = long.MaxValue;
165 private long minDirectmessageSent = long.MaxValue;
167 //private FavoriteQueue favQueue;
169 private HttpTwitter twCon = new HttpTwitter();
170 private TwitterApi Api { get; }
172 //private List<PostClass> _deletemessages = new List<PostClass>();
174 public Twitter() : this(new TwitterApi())
178 public Twitter(TwitterApi api)
181 this.Configuration = TwitterConfiguration.DefaultConfiguration();
184 public TwitterApiAccessLevel AccessLevel
188 return MyCommon.TwitterApiInfo.AccessLevel;
192 protected void ResetApiStatus()
194 MyCommon.TwitterApiInfo.Reset();
197 public void Authenticate(string username, string password)
199 this.ResetApiStatus();
205 res = twCon.AuthUserAndPass(username, password, ref content);
209 throw new WebApiException("Err:" + ex.Message, ex);
212 this.CheckStatusCode(res, content);
214 _uname = username.ToLowerInvariant();
215 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
218 public string StartAuthentication()
221 this.ResetApiStatus();
224 string pinPageUrl = null;
225 var res = twCon.AuthGetRequestToken(ref pinPageUrl);
227 throw new WebApiException("Err:Failed to access auth server.");
233 throw new WebApiException("Err:Failed to access auth server.", ex);
237 public void Authenticate(string pinCode)
239 this.ResetApiStatus();
244 res = twCon.AuthGetAccessToken(pinCode);
248 throw new WebApiException("Err:Failed to access auth acc server.", ex);
251 this.CheckStatusCode(res, null);
253 _uname = Username.ToLowerInvariant();
254 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
257 public void ClearAuthInfo()
259 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
260 this.ResetApiStatus();
261 twCon.ClearAuthInfo();
264 public void VerifyCredentials()
270 res = twCon.VerifyCredentials(ref content);
274 throw new WebApiException("Err:" + ex.Message, ex);
277 this.CheckStatusCode(res, content);
281 var user = TwitterUser.ParseJson(content);
283 this.twCon.AuthenticatedUserId = user.Id;
284 this.UpdateUserStats(user);
286 catch (SerializationException ex)
288 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
289 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
293 public void Initialize(string token, string tokenSecret, string username, long userId)
296 if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
298 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
300 this.ResetApiStatus();
301 twCon.Initialize(token, tokenSecret, username, userId);
302 _uname = username.ToLowerInvariant();
303 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
306 public string PreProcessUrl(string orgData)
310 //var IDNConveter = new IdnMapping();
311 var href = "<a href=\"";
315 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
319 posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
320 posl1 += href.Length;
321 posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
322 urlStr = orgData.Substring(posl1, posl2 - posl1);
324 if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
325 && !urlStr.StartsWith("https://", StringComparison.Ordinal)
326 && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
331 var replacedUrl = MyCommon.IDNEncode(urlStr);
332 if (replacedUrl == null) continue;
333 if (replacedUrl == urlStr) continue;
335 orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
346 private string GetPlainText(string orgData)
348 return WebUtility.HtmlDecode(Regex.Replace(orgData, "(?<tagStart><a [^>]+>)(?<text>[^<]+)(?<tagEnd></a>)", "${text}"));
351 // htmlの簡易サニタイズ(詳細表示に不要なタグの除去)
353 private string SanitizeHtml(string orgdata)
355 var retdata = orgdata;
357 retdata = Regex.Replace(retdata, "<(script|object|applet|image|frameset|fieldset|legend|style).*" +
358 "</(script|object|applet|image|frameset|fieldset|legend|style)>", "", RegexOptions.IgnoreCase);
360 retdata = Regex.Replace(retdata, "<(frame|link|iframe|img)>", "", RegexOptions.IgnoreCase);
365 private string AdjustHtml(string orgData)
367 var retStr = orgData;
368 //var m = Regex.Match(retStr, "<a [^>]+>[#|#](?<1>[a-zA-Z0-9_]+)</a>");
373 // _hashList.Add("#" + m.Groups(1).Value);
377 retStr = Regex.Replace(retStr, "<a [^>]*href=\"/", "<a href=\"https://twitter.com/");
378 retStr = retStr.Replace("<a href=", "<a target=\"_self\" href=");
379 retStr = Regex.Replace(retStr, @"(\r\n?|\n)", "<br>"); // CRLF, CR, LF は全て <br> に置換する
381 //半角スペースを置換(Thanks @anis774)
385 ret = EscapeSpace(ref retStr);
388 return SanitizeHtml(retStr);
391 private bool EscapeSpace(ref string html)
393 //半角スペースを置換(Thanks @anis774)
395 for (int i = 0; i < html.Length; i++)
406 if ((!isTag) && (html[i] == ' '))
408 html = html.Remove(i, 1);
409 html = html.Insert(i, " ");
416 private struct PostInfo
418 public string CreatedAt;
421 public string UserId;
422 public PostInfo(string Created, string IdStr, string txt, string uid)
429 public bool Equals(PostInfo dst)
431 if (this.CreatedAt == dst.CreatedAt && this.Id == dst.Id && this.Text == dst.Text && this.UserId == dst.UserId)
442 static private PostInfo _prev = new PostInfo("", "", "", "");
443 private bool IsPostRestricted(TwitterStatus status)
445 var _current = new PostInfo("", "", "", "");
447 _current.CreatedAt = status.CreatedAt;
448 _current.Id = status.IdStr;
449 if (status.Text == null)
455 _current.Text = status.Text;
457 _current.UserId = status.User.IdStr;
459 if (_current.Equals(_prev))
463 _prev.CreatedAt = _current.CreatedAt;
464 _prev.Id = _current.Id;
465 _prev.Text = _current.Text;
466 _prev.UserId = _current.UserId;
471 public async Task PostStatus(string postStr, long? reply_to, IReadOnlyList<long> mediaIds = null)
473 this.CheckAccountState();
475 if (mediaIds == null &&
476 Twitter.DMSendTextRegex.IsMatch(postStr))
478 await this.SendDirectMessage(postStr)
479 .ConfigureAwait(false);
483 var response = await this.Api.StatusesUpdate(postStr, reply_to, mediaIds)
484 .ConfigureAwait(false);
486 var status = await response.LoadJsonAsync()
487 .ConfigureAwait(false);
489 this.UpdateUserStats(status.User);
491 if (IsPostRestricted(status))
493 throw new WebApiException("OK:Delaying?");
497 public async Task PostStatusWithMultipleMedia(string postStr, long? reply_to, IMediaItem[] mediaItems)
499 this.CheckAccountState();
501 if (Twitter.DMSendTextRegex.IsMatch(postStr))
503 await this.SendDirectMessage(postStr)
504 .ConfigureAwait(false);
508 if (mediaItems.Length == 0)
509 throw new WebApiException("Err:Invalid Files!");
511 var uploadTasks = from m in mediaItems
512 select this.UploadMedia(m);
514 var mediaIds = await Task.WhenAll(uploadTasks)
515 .ConfigureAwait(false);
517 await this.PostStatus(postStr, reply_to, mediaIds)
518 .ConfigureAwait(false);
521 public async Task<long> UploadMedia(IMediaItem item)
523 this.CheckAccountState();
525 var response = await this.Api.MediaUpload(item)
526 .ConfigureAwait(false);
528 var media = await response.LoadJsonAsync()
529 .ConfigureAwait(false);
531 return media.MediaId;
534 public async Task SendDirectMessage(string postStr)
536 this.CheckAccountState();
537 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
539 var mc = Twitter.DMSendTextRegex.Match(postStr);
541 var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
542 .ConfigureAwait(false);
544 var dm = await response.LoadJsonAsync()
545 .ConfigureAwait(false);
547 this.UpdateUserStats(dm.Sender);
550 public void PostRetweet(long id, bool read)
552 this.CheckAccountState();
556 var post = TabInformations.GetInstance()[id];
559 throw new WebApiException("Err:Target isn't found.");
561 if (TabInformations.GetInstance()[id].RetweetedId != null)
563 target = TabInformations.GetInstance()[id].RetweetedId.Value; //再RTの場合は元発言をRT
570 res = twCon.RetweetStatus(target, ref content);
574 throw new WebApiException("Err:" + ex.Message, ex);
577 this.CheckStatusCode(res, content);
579 TwitterStatus status;
582 status = TwitterStatus.ParseJson(content);
584 catch(SerializationException ex)
586 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
587 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
591 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
592 throw new WebApiException("Err:Invalid Json!", content, ex);
596 post = CreatePostsFromStatusData(status);
598 throw new WebApiException("Invalid Json!", content);
603 if (TabInformations.GetInstance().ContainsKey(post.StatusId))
607 if (post.RetweetedId == null)
608 throw new WebApiException("Invalid Json!", content);
614 if (_readOwnPost) post.IsRead = true;
617 TabInformations.GetInstance().AddPost(post);
620 public string Username
624 return twCon.AuthenticatedUsername;
632 return twCon.AuthenticatedUserId;
636 public string Password
640 return twCon.Password;
644 private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
645 public static MyCommon.ACCOUNT_STATE AccountState
649 return _accountState;
653 _accountState = value;
657 public bool RestrictFavCheck { get; set; }
660 public void GetTweenBinary(string strVer)
665 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/Tween" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
666 Path.Combine(MyCommon.settingPath, "TweenNew.exe")))
668 throw new WebApiException("Err:Download failed");
671 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, "en")))
673 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, "en"));
675 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenResEn" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
676 Path.Combine(Path.Combine(MyCommon.settingPath, "en"), "Tween.resourcesNew.dll")))
678 throw new WebApiException("Err:Download failed");
680 //その他言語圏のリソース。取得失敗しても継続
683 if (!Thread.CurrentThread.CurrentUICulture.IsNeutralCulture)
685 var idx = Thread.CurrentThread.CurrentUICulture.Name.LastIndexOf('-');
688 curCul = Thread.CurrentThread.CurrentUICulture.Name.Substring(0, idx);
692 curCul = Thread.CurrentThread.CurrentUICulture.Name;
697 curCul = Thread.CurrentThread.CurrentUICulture.Name;
699 if (!string.IsNullOrEmpty(curCul) && curCul != "en" && curCul != "ja")
701 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul)))
703 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul));
705 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
706 Path.Combine(Path.Combine(MyCommon.settingPath, curCul), "Tween.resourcesNew.dll")))
708 //return "Err:Download failed";
713 if (!Thread.CurrentThread.CurrentCulture.IsNeutralCulture)
715 var idx = Thread.CurrentThread.CurrentCulture.Name.LastIndexOf('-');
718 curCul2 = Thread.CurrentThread.CurrentCulture.Name.Substring(0, idx);
722 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
727 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
729 if (!string.IsNullOrEmpty(curCul2) && curCul2 != "en" && curCul2 != curCul)
731 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul2)))
733 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul2));
735 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul2 + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
736 Path.Combine(Path.Combine(MyCommon.settingPath, curCul2), "Tween.resourcesNew.dll")))
738 //return "Err:Download failed";
743 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenUp3.gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
744 Path.Combine(MyCommon.settingPath, "TweenUp3.exe")))
746 throw new WebApiException("Err:Download failed");
749 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenDll" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
750 Path.Combine(MyCommon.settingPath, "TweenNew.XmlSerializers.dll")))
752 throw new WebApiException("Err:Download failed");
757 throw new WebApiException("Err:Download failed", ex);
762 public bool ReadOwnPost
770 _readOwnPost = value;
774 public int FollowersCount { get; private set; }
775 public int FriendsCount { get; private set; }
776 public int StatusesCount { get; private set; }
777 public string Location { get; private set; } = "";
778 public string Bio { get; private set; } = "";
780 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
781 private void UpdateUserStats(TwitterUser self)
783 this.FollowersCount = self.FollowersCount;
784 this.FriendsCount = self.FriendsCount;
785 this.StatusesCount = self.StatusesCount;
786 this.Location = self.Location;
787 this.Bio = self.Description;
791 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
793 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
795 return count >= 20 && count <= GetMaxApiResultCount(type);
799 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
801 public static bool VerifyMoreApiResultCount(int count)
803 return count >= 20 && count <= 200;
807 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
809 public static bool VerifyFirstApiResultCount(int count)
811 return count >= 20 && count <= 200;
815 /// WORKERTYPEに応じた取得可能な最大件数を取得する
817 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
819 // 参照: REST APIs - 各endpointのcountパラメータ
820 // https://dev.twitter.com/rest/public
823 case MyCommon.WORKERTYPE.Timeline:
824 case MyCommon.WORKERTYPE.Reply:
825 case MyCommon.WORKERTYPE.UserTimeline:
826 case MyCommon.WORKERTYPE.Favorites:
827 case MyCommon.WORKERTYPE.DirectMessegeRcv:
828 case MyCommon.WORKERTYPE.DirectMessegeSnt:
829 case MyCommon.WORKERTYPE.List: // 不明
832 case MyCommon.WORKERTYPE.PublicSearch:
836 throw new InvalidOperationException("Invalid type: " + type);
841 /// WORKERTYPEに応じた取得件数を取得する
843 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
845 if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
846 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
851 if (SettingCommon.Instance.UseAdditionalCount)
855 case MyCommon.WORKERTYPE.Favorites:
856 if (SettingCommon.Instance.FavoritesCountApi != 0)
857 return SettingCommon.Instance.FavoritesCountApi;
859 case MyCommon.WORKERTYPE.List:
860 if (SettingCommon.Instance.ListCountApi != 0)
861 return SettingCommon.Instance.ListCountApi;
863 case MyCommon.WORKERTYPE.PublicSearch:
864 if (SettingCommon.Instance.SearchCountApi != 0)
865 return SettingCommon.Instance.SearchCountApi;
867 case MyCommon.WORKERTYPE.UserTimeline:
868 if (SettingCommon.Instance.UserTimelineCountApi != 0)
869 return SettingCommon.Instance.UserTimelineCountApi;
872 if (more && SettingCommon.Instance.MoreCountApi != 0)
874 return Math.Min(SettingCommon.Instance.MoreCountApi, GetMaxApiResultCount(type));
876 if (startup && SettingCommon.Instance.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
878 return Math.Min(SettingCommon.Instance.FirstCountApi, GetMaxApiResultCount(type));
883 var count = SettingCommon.Instance.CountApi;
885 if (type == MyCommon.WORKERTYPE.Reply)
886 count = SettingCommon.Instance.CountApiReply;
888 return Math.Min(count, GetMaxApiResultCount(type));
891 public void GetTimelineApi(bool read,
892 MyCommon.WORKERTYPE gType,
896 this.CheckAccountState();
900 var count = GetApiResultCount(gType, more, startup);
904 if (gType == MyCommon.WORKERTYPE.Timeline)
908 res = twCon.HomeTimeline(count, this.minHomeTimeline, null, ref content);
912 res = twCon.HomeTimeline(count, null, null, ref content);
919 res = twCon.Mentions(count, this.minMentions, null, ref content);
923 res = twCon.Mentions(count, null, null, ref content);
929 throw new WebApiException("Err:" + ex.Message, ex);
932 this.CheckStatusCode(res, content);
934 var minimumId = CreatePostsFromJson(content, gType, null, read);
936 if (minimumId != null)
938 if (gType == MyCommon.WORKERTYPE.Timeline)
939 this.minHomeTimeline = minimumId.Value;
941 this.minMentions = minimumId.Value;
945 public void GetUserTimelineApi(bool read,
950 this.CheckAccountState();
954 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
958 if (string.IsNullOrEmpty(userName))
960 var target = tab.User;
961 if (string.IsNullOrEmpty(target)) return;
963 res = twCon.UserTimeline(null, target, count, null, null, ref content);
969 res = twCon.UserTimeline(null, userName, count, tab.OldestId, null, ref content);
973 res = twCon.UserTimeline(null, userName, count, null, null, ref content);
979 throw new WebApiException("Err:" + ex.Message, ex);
982 if (res == HttpStatusCode.Unauthorized)
983 throw new WebApiException("Err:@" + userName + "'s Tweets are protected.");
985 this.CheckStatusCode(res, content);
987 var minimumId = CreatePostsFromJson(content, MyCommon.WORKERTYPE.UserTimeline, tab, read);
989 if (minimumId != null)
990 tab.OldestId = minimumId.Value;
993 public async Task<PostClass> GetStatusApi(bool read, long id)
995 this.CheckAccountState();
997 var status = await this.Api.StatusesShow(id)
998 .ConfigureAwait(false);
1000 var item = CreatePostsFromStatusData(status);
1002 throw new WebApiException("Err:Can't create post");
1005 if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
1010 public async Task GetStatusApi(bool read, long id, TabClass tab)
1012 var post = await this.GetStatusApi(read, id)
1013 .ConfigureAwait(false);
1015 //非同期アイコン取得&StatusDictionaryに追加
1016 if (tab != null && tab.IsInnerStorageTabType)
1017 tab.AddPostToInnerStorage(post);
1019 TabInformations.GetInstance().AddPost(post);
1022 private PostClass CreatePostsFromStatusData(TwitterStatus status)
1024 return CreatePostsFromStatusData(status, false);
1027 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
1029 var post = new PostClass();
1030 TwitterEntities entities;
1033 post.StatusId = status.Id;
1034 if (status.RetweetedStatus != null)
1036 var retweeted = status.RetweetedStatus;
1038 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
1041 post.RetweetedId = retweeted.Id;
1043 post.TextFromApi = retweeted.Text;
1044 entities = retweeted.MergedEntities;
1045 sourceHtml = retweeted.Source;
1047 post.InReplyToStatusId = retweeted.InReplyToStatusId;
1048 post.InReplyToUser = retweeted.InReplyToScreenName;
1049 post.InReplyToUserId = status.InReplyToUserId;
1058 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1059 post.IsFav = tc.Contains(retweeted.Id);
1062 if (retweeted.Coordinates != null)
1063 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
1066 var user = retweeted.User;
1068 if (user == null || user.ScreenName == null || status.User.ScreenName == null) return null;
1070 post.UserId = user.Id;
1071 post.ScreenName = user.ScreenName;
1072 post.Nickname = user.Name.Trim();
1073 post.ImageUrl = user.ProfileImageUrlHttps;
1074 post.IsProtect = user.Protected;
1077 post.RetweetedBy = status.User.ScreenName;
1078 post.RetweetedByUserId = status.User.Id;
1079 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
1083 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
1085 post.TextFromApi = status.Text;
1086 entities = status.MergedEntities;
1087 sourceHtml = status.Source;
1088 post.InReplyToStatusId = status.InReplyToStatusId;
1089 post.InReplyToUser = status.InReplyToScreenName;
1090 post.InReplyToUserId = status.InReplyToUserId;
1099 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1100 post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
1103 if (status.Coordinates != null)
1104 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
1107 var user = status.User;
1109 if (user == null || user.ScreenName == null) return null;
1111 post.UserId = user.Id;
1112 post.ScreenName = user.ScreenName;
1113 post.Nickname = user.Name.Trim();
1114 post.ImageUrl = user.ProfileImageUrlHttps;
1115 post.IsProtect = user.Protected;
1116 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
1119 string textFromApi = post.TextFromApi;
1120 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
1121 post.TextFromApi = textFromApi;
1122 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
1123 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1124 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1126 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
1127 .Where(x => x != post.StatusId && x != post.RetweetedId)
1128 .Distinct().ToArray();
1130 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
1131 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1135 var source = ParseSource(sourceHtml);
1136 post.Source = source.Item1;
1137 post.SourceUri = source.Item2;
1139 post.IsReply = post.ReplyToList.Contains(_uname);
1140 post.IsExcludeReply = false;
1148 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
1156 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
1158 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
1160 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
1162 return GetQuoteTweetStatusIds(urls);
1165 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
1167 foreach (var url in urls)
1169 var match = Twitter.StatusUrlRegex.Match(url);
1173 if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
1174 yield return statusId;
1179 private long? CreatePostsFromJson(string content, MyCommon.WORKERTYPE gType, TabClass tab, bool read)
1181 TwitterStatus[] items;
1184 items = TwitterStatus.ParseJsonArray(content);
1186 catch(SerializationException ex)
1188 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1189 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1193 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1194 throw new WebApiException("Invalid Json!", content, ex);
1197 long? minimumId = null;
1199 foreach (var status in items)
1201 PostClass post = null;
1202 post = CreatePostsFromStatusData(status);
1203 if (post == null) continue;
1205 if (minimumId == null || minimumId.Value > post.StatusId)
1206 minimumId = post.StatusId;
1213 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1217 if (tab.Contains(post.StatusId)) continue;
1222 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
1223 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
1226 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1228 //非同期アイコン取得&StatusDictionaryに追加
1229 if (tab != null && tab.IsInnerStorageTabType)
1230 tab.AddPostToInnerStorage(post);
1232 TabInformations.GetInstance().AddPost(post);
1238 private long? CreatePostsFromSearchJson(string content, TabClass tab, bool read, int count, bool more)
1240 TwitterSearchResult items;
1243 items = TwitterSearchResult.ParseJson(content);
1245 catch (SerializationException ex)
1247 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1248 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1250 catch (Exception ex)
1252 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1253 throw new WebApiException("Invalid Json!", content, ex);
1256 long? minimumId = null;
1258 foreach (var result in items.Statuses)
1260 var post = CreatePostsFromStatusData(result);
1264 if (minimumId == null || minimumId.Value > post.StatusId)
1265 minimumId = post.StatusId;
1267 if (!more && post.StatusId > tab.SinceId) tab.SinceId = post.StatusId;
1273 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1277 if (tab.Contains(post.StatusId)) continue;
1282 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
1284 //非同期アイコン取得&StatusDictionaryに追加
1285 if (tab != null && tab.IsInnerStorageTabType)
1286 tab.AddPostToInnerStorage(post);
1288 TabInformations.GetInstance().AddPost(post);
1294 private void CreateFavoritePostsFromJson(string content, bool read)
1296 TwitterStatus[] item;
1299 item = TwitterStatus.ParseJsonArray(content);
1301 catch (SerializationException ex)
1303 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1304 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1306 catch (Exception ex)
1308 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1309 throw new WebApiException("Invalid Json!", content, ex);
1312 var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1314 foreach (var status in item)
1319 if (favTab.Contains(status.Id)) continue;
1322 var post = CreatePostsFromStatusData(status, true);
1323 if (post == null) continue;
1327 TabInformations.GetInstance().AddPost(post);
1331 public void GetListStatus(bool read,
1338 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
1344 res = twCon.GetListsStatuses(tab.ListInfo.UserId, tab.ListInfo.Id, count, tab.OldestId, null, SettingCommon.Instance.IsListsIncludeRts, ref content);
1348 res = twCon.GetListsStatuses(tab.ListInfo.UserId, tab.ListInfo.Id, count, null, null, SettingCommon.Instance.IsListsIncludeRts, ref content);
1353 throw new WebApiException("Err:" + ex.Message, ex);
1356 this.CheckStatusCode(res, content);
1358 var minimumId = CreatePostsFromJson(content, MyCommon.WORKERTYPE.List, tab, read);
1360 if (minimumId != null)
1361 tab.OldestId = minimumId.Value;
1365 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1367 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1368 internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1370 if (!posts.ContainsKey(startStatusId))
1371 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1373 var nextPost = posts[startStatusId];
1374 while (nextPost.InReplyToStatusId != null)
1376 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1378 nextPost = posts[nextPost.InReplyToStatusId.Value];
1384 public async Task GetRelatedResult(bool read, TabClass tab)
1386 var relPosts = new Dictionary<Int64, PostClass>();
1387 if (tab.RelationTargetPost.TextFromApi.Contains("@") && tab.RelationTargetPost.InReplyToStatusId == null)
1390 var p = TabInformations.GetInstance()[tab.RelationTargetPost.StatusId];
1391 if (p != null && p.InReplyToStatusId != null)
1393 tab.RelationTargetPost = p;
1397 p = await this.GetStatusApi(read, tab.RelationTargetPost.StatusId)
1398 .ConfigureAwait(false);
1399 tab.RelationTargetPost = p;
1402 relPosts.Add(tab.RelationTargetPost.StatusId, tab.RelationTargetPost);
1404 Exception lastException = null;
1406 // in_reply_to_status_id を使用してリプライチェインを辿る
1407 var nextPost = FindTopOfReplyChain(relPosts, tab.RelationTargetPost.StatusId);
1409 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1411 var inReplyToId = nextPost.InReplyToStatusId.Value;
1413 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1414 if (inReplyToPost == null)
1418 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1419 .ConfigureAwait(false);
1421 catch (WebApiException ex)
1428 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1430 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1433 //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1434 var text = tab.RelationTargetPost.Text;
1435 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1436 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1437 foreach (var _match in ma)
1440 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1442 if (relPosts.ContainsKey(_statusId))
1445 var p = TabInformations.GetInstance()[_statusId];
1450 p = await this.GetStatusApi(read, _statusId)
1451 .ConfigureAwait(false);
1453 catch (WebApiException ex)
1461 relPosts.Add(p.StatusId, p);
1465 relPosts.Values.ToList().ForEach(p =>
1467 if (p.IsMe && !read && this._readOwnPost)
1472 tab.AddPostToInnerStorage(p);
1475 if (lastException != null)
1476 throw new WebApiException(lastException.Message, lastException);
1479 public void GetSearch(bool read,
1485 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1487 long? sinceId = null;
1490 maxId = tab.OldestId - 1;
1494 sinceId = tab.SinceId;
1499 // TODO:一時的に40>100件に 件数変更UI作成の必要あり
1500 res = twCon.Search(tab.SearchWords, tab.SearchLang, count, maxId, sinceId, ref content);
1504 throw new WebApiException("Err:" + ex.Message, ex);
1508 case HttpStatusCode.BadRequest:
1509 throw new WebApiException("Invalid query", content);
1510 case HttpStatusCode.NotFound:
1511 throw new WebApiException("Invalid query", content);
1512 case HttpStatusCode.PaymentRequired: //API Documentには420と書いてあるが、該当コードがないので402にしてある
1513 throw new WebApiException("Search API Limit?", content);
1514 case HttpStatusCode.OK:
1517 throw new WebApiException("Err:" + res.ToString() + "(" + MethodBase.GetCurrentMethod().Name + ")", content);
1520 if (!TabInformations.GetInstance().ContainsTab(tab))
1523 var minimumId = this.CreatePostsFromSearchJson(content, tab, read, count, more);
1525 if (minimumId != null)
1526 tab.OldestId = minimumId.Value;
1529 private void CreateDirectMessagesFromJson(string content, MyCommon.WORKERTYPE gType, bool read)
1531 TwitterDirectMessage[] item;
1534 if (gType == MyCommon.WORKERTYPE.UserStream)
1536 item = new[] { TwitterStreamEventDirectMessage.ParseJson(content).DirectMessage };
1540 item = TwitterDirectMessage.ParseJsonArray(content);
1543 catch(SerializationException ex)
1545 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1546 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1550 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1551 throw new WebApiException("Invalid Json!", content, ex);
1554 foreach (var message in item)
1556 var post = new PostClass();
1559 post.StatusId = message.Id;
1560 if (gType != MyCommon.WORKERTYPE.UserStream)
1562 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1564 if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1568 if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1575 if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1579 post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1581 var textFromApi = message.Text;
1583 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
1584 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
1585 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1586 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1589 post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
1591 post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1592 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1597 if (gType == MyCommon.WORKERTYPE.UserStream)
1599 if (twCon.AuthenticatedUsername.Equals(message.Recipient.ScreenName, StringComparison.CurrentCultureIgnoreCase))
1601 user = message.Sender;
1607 user = message.Recipient;
1614 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1616 user = message.Sender;
1622 user = message.Recipient;
1628 post.UserId = user.Id;
1629 post.ScreenName = user.ScreenName;
1630 post.Nickname = user.Name.Trim();
1631 post.ImageUrl = user.ProfileImageUrlHttps;
1632 post.IsProtect = user.Protected;
1636 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1637 MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1642 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1643 post.IsReply = false;
1644 post.IsExcludeReply = false;
1647 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1648 dmTab.AddPostToInnerStorage(post);
1652 public void GetDirectMessageApi(bool read,
1653 MyCommon.WORKERTYPE gType,
1656 this.CheckAccountState();
1657 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1661 var count = GetApiResultCount(gType, more, false);
1665 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1669 res = twCon.DirectMessages(count, minDirectmessage, null, ref content);
1673 res = twCon.DirectMessages(count, null, null, ref content);
1680 res = twCon.DirectMessagesSent(count, minDirectmessageSent, null, ref content);
1684 res = twCon.DirectMessagesSent(count, null, null, ref content);
1690 throw new WebApiException("Err:" + ex.Message, ex);
1693 this.CheckStatusCode(res, content);
1695 CreateDirectMessagesFromJson(content, gType, read);
1698 public void GetFavoritesApi(bool read,
1701 this.CheckAccountState();
1705 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
1709 res = twCon.Favorites(count, ref content);
1713 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1716 this.CheckStatusCode(res, content);
1718 CreateFavoritePostsFromJson(content, read);
1721 private string ReplaceTextFromApi(string text, TwitterEntities entities)
1723 if (entities != null)
1725 if (entities.Urls != null)
1727 foreach (var m in entities.Urls)
1729 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1732 if (entities.Media != null)
1734 foreach (var m in entities.Media)
1736 if (m.AltText != null)
1738 text = text.Replace(m.Url, string.Format(Properties.Resources.ImageAltText, m.AltText));
1742 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1753 /// <exception cref="WebApiException"/>
1754 public async Task RefreshFollowerIds()
1756 if (MyCommon._endingFlag) return;
1759 var newFollowerIds = new HashSet<long>();
1762 var ret = await this.Api.FollowersIds(cursor)
1763 .ConfigureAwait(false);
1765 if (ret.Ids == null)
1766 throw new WebApiException("ret.ids == null");
1768 newFollowerIds.UnionWith(ret.Ids);
1769 cursor = ret.NextCursor;
1770 } while (cursor != 0);
1772 this.followerId = newFollowerIds;
1773 TabInformations.GetInstance().RefreshOwl(this.followerId);
1775 this._GetFollowerResult = true;
1778 public bool GetFollowersSuccess
1782 return _GetFollowerResult;
1787 /// RT 非表示ユーザーを更新します
1789 /// <exception cref="WebApiException"/>
1790 public void RefreshNoRetweetIds()
1792 if (MyCommon._endingFlag) return;
1794 this.noRTId = this.NoRetweetIdsApi();
1796 this._GetNoRetweetResult = true;
1799 private long[] NoRetweetIdsApi()
1801 this.CheckAccountState();
1807 res = twCon.NoRetweetIds(ref content);
1811 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
1814 this.CheckStatusCode(res, content);
1818 return MyCommon.CreateDataFromJson<long[]>(content);
1820 catch(SerializationException e)
1822 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
1823 MyCommon.TraceOut(ex);
1828 var ex = new WebApiException("Err:Invalid Json!", content, e);
1829 MyCommon.TraceOut(ex);
1834 public bool GetNoRetweetSuccess
1838 return _GetNoRetweetResult;
1843 /// t.co の文字列長などの設定情報を更新します
1845 /// <exception cref="WebApiException"/>
1846 public void RefreshConfiguration()
1848 this.Configuration = this.ConfigurationApi();
1851 private TwitterConfiguration ConfigurationApi()
1857 res = twCon.GetConfiguration(ref content);
1861 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
1864 this.CheckStatusCode(res, content);
1868 return TwitterConfiguration.ParseJson(content);
1870 catch(SerializationException e)
1872 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
1873 MyCommon.TraceOut(ex);
1878 var ex = new WebApiException("Err:Invalid Json!", content, e);
1879 MyCommon.TraceOut(ex);
1884 public void GetListsApi()
1886 this.CheckAccountState();
1889 IEnumerable<ListElement> lists;
1894 res = twCon.GetLists(this.Username, ref content);
1896 catch (Exception ex)
1898 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1901 this.CheckStatusCode(res, content);
1905 lists = TwitterList.ParseJsonArray(content)
1906 .Select(x => new ListElement(x, this));
1908 catch (SerializationException ex)
1910 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1911 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1913 catch (Exception ex)
1915 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1916 throw new WebApiException("Err:Invalid Json!", content, ex);
1921 res = twCon.GetListsSubscriptions(this.Username, ref content);
1923 catch (Exception ex)
1925 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1928 this.CheckStatusCode(res, content);
1932 lists = lists.Concat(TwitterList.ParseJsonArray(content)
1933 .Select(x => new ListElement(x, this)));
1935 catch (SerializationException ex)
1937 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1938 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1940 catch (Exception ex)
1942 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1943 throw new WebApiException("Err:Invalid Json!", content, ex);
1946 TabInformations.GetInstance().SubscribableLists = lists.ToList();
1949 public void DeleteList(string list_id)
1956 res = twCon.DeleteListID(this.Username, list_id, ref content);
1960 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1963 this.CheckStatusCode(res, content);
1966 public ListElement EditList(string list_id, string new_name, bool isPrivate, string description)
1973 res = twCon.UpdateListID(this.Username, list_id, new_name, isPrivate, description, ref content);
1977 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1980 this.CheckStatusCode(res, content);
1984 var le = TwitterList.ParseJson(content);
1985 return new ListElement(le, this);
1987 catch(SerializationException ex)
1989 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1990 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1994 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1995 throw new WebApiException("Err:Invalid Json!", content, ex);
1999 public long GetListMembers(string list_id, List<UserInfo> lists, long cursor)
2001 this.CheckAccountState();
2007 res = twCon.GetListMembers(this.Username, list_id, cursor, ref content);
2011 throw new WebApiException("Err:" + ex.Message);
2014 this.CheckStatusCode(res, content);
2018 var users = TwitterUsers.ParseJson(content);
2019 Array.ForEach<TwitterUser>(
2021 u => lists.Add(new UserInfo(u)));
2023 return users.NextCursor;
2025 catch(SerializationException ex)
2027 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2028 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2032 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2033 throw new WebApiException("Err:Invalid Json!", content, ex);
2037 public void CreateListApi(string listName, bool isPrivate, string description)
2039 this.CheckAccountState();
2045 res = twCon.CreateLists(listName, isPrivate, description, ref content);
2049 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2052 this.CheckStatusCode(res, content);
2056 var le = TwitterList.ParseJson(content);
2057 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(le, this));
2059 catch(SerializationException ex)
2061 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
2062 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2066 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2067 throw new WebApiException("Err:Invalid Json!", content, ex);
2071 public bool ContainsUserAtList(string listId, string user)
2073 this.CheckAccountState();
2080 res = this.twCon.ShowListMember(listId, user, ref content);
2084 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2087 if (res == HttpStatusCode.NotFound)
2092 this.CheckStatusCode(res, content);
2096 TwitterUser.ParseJson(content);
2105 public void AddUserToList(string listId, string user)
2112 res = twCon.CreateListMembers(listId, user, ref content);
2116 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2119 this.CheckStatusCode(res, content);
2122 public void RemoveUserToList(string listId, string user)
2129 res = twCon.DeleteListMembers(listId, user, ref content);
2133 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
2136 this.CheckStatusCode(res, content);
2139 public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
2141 if (entities != null)
2143 if (entities.Hashtags != null)
2147 this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
2150 if (entities.UserMentions != null)
2152 foreach (var ent in entities.UserMentions)
2154 var screenName = ent.ScreenName.ToLowerInvariant();
2155 if (!AtList.Contains(screenName))
2156 AtList.Add(screenName);
2159 if (entities.Media != null)
2163 foreach (var ent in entities.Media)
2165 if (!media.Any(x => x.Url == ent.MediaUrl))
2167 if (ent.VideoInfo != null &&
2168 ent.Type == "animated_gif" || ent.Type == "video")
2170 //var videoUrl = ent.VideoInfo.Variants
2171 // .Where(v => v.ContentType == "video/mp4")
2172 // .OrderByDescending(v => v.Bitrate)
2173 // .Select(v => v.Url).FirstOrDefault();
2174 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, ent.ExpandedUrl));
2177 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, videoUrl: null));
2184 // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
2185 text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
2187 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>");
2188 text = PreProcessUrl(text); //IDN置換
2193 private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
2196 /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
2198 public static Tuple<string, Uri> ParseSource(string sourceHtml)
2200 if (string.IsNullOrEmpty(sourceHtml))
2201 return Tuple.Create<string, Uri>("", null);
2206 // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
2208 var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
2211 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
2214 var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
2215 sourceUri = new Uri(SourceUriBase, uriStr);
2217 catch (UriFormatException)
2224 sourceText = WebUtility.HtmlDecode(sourceHtml);
2228 return Tuple.Create(sourceText, sourceUri);
2231 public TwitterApiStatus GetInfoApi()
2233 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
2235 if (MyCommon._endingFlag) return null;
2241 res = twCon.RateLimitStatus(ref content);
2245 this.ResetApiStatus();
2249 this.CheckStatusCode(res, content);
2253 MyCommon.TwitterApiInfo.UpdateFromJson(content);
2254 return MyCommon.TwitterApiInfo;
2256 catch (Exception ex)
2258 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2259 MyCommon.TwitterApiInfo.Reset();
2265 /// ブロック中のユーザーを更新します
2267 /// <exception cref="WebApiException"/>
2268 public void RefreshBlockIds()
2270 if (MyCommon._endingFlag) return;
2273 var newBlockIds = new HashSet<long>();
2276 var ret = this.GetBlockIdsApi(cursor);
2277 newBlockIds.UnionWith(ret.Ids);
2278 cursor = ret.NextCursor;
2279 } while (cursor != 0);
2281 newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
2283 TabInformations.GetInstance().BlockIds = newBlockIds;
2286 public TwitterIds GetBlockIdsApi(long cursor)
2288 this.CheckAccountState();
2294 res = twCon.GetBlockUserIds(ref content, cursor);
2298 throw new WebApiException("Err:" + e.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", e);
2301 this.CheckStatusCode(res, content);
2305 return TwitterIds.ParseJson(content);
2307 catch(SerializationException e)
2309 var ex = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, e);
2310 MyCommon.TraceOut(ex);
2315 var ex = new WebApiException("Err:Invalid Json!", content, e);
2316 MyCommon.TraceOut(ex);
2322 /// ミュート中のユーザーIDを更新します
2324 /// <exception cref="WebApiException"/>
2325 public async Task RefreshMuteUserIdsAsync()
2327 if (MyCommon._endingFlag) return;
2329 var ids = await TwitterIds.GetAllItemsAsync(this.GetMuteUserIdsApiAsync)
2330 .ConfigureAwait(false);
2332 TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
2335 public async Task<TwitterIds> GetMuteUserIdsApiAsync(long cursor)
2341 var res = await Task.Run(() => twCon.GetMuteUserIds(ref content, cursor))
2342 .ConfigureAwait(false);
2344 this.CheckStatusCode(res, content);
2346 return TwitterIds.ParseJson(content);
2348 catch (WebException ex)
2350 var ex2 = new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", content, ex);
2351 MyCommon.TraceOut(ex2);
2354 catch (SerializationException ex)
2356 var ex2 = new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
2357 MyCommon.TraceOut(ex2);
2362 public string[] GetHashList()
2367 hashArray = _hashList.ToArray();
2373 public string AccessToken
2377 return twCon.AccessToken;
2381 public string AccessTokenSecret
2385 return twCon.AccessTokenSecret;
2389 private void CheckAccountState()
2391 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2392 throw new WebApiException("Auth error. Check your account");
2395 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
2397 if (!this.AccessLevel.HasFlag(accessLevelFlags))
2398 throw new WebApiException("Auth Err:try to re-authorization.");
2401 private void CheckStatusCode(HttpStatusCode httpStatus, string responseText,
2402 [CallerMemberName] string callerMethodName = "")
2404 if (httpStatus == HttpStatusCode.OK)
2406 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2410 if (string.IsNullOrWhiteSpace(responseText))
2412 if (httpStatus == HttpStatusCode.Unauthorized)
2413 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2415 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")");
2420 var errors = TwitterError.ParseJson(responseText).Errors;
2421 if (errors == null || !errors.Any())
2423 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2426 foreach (var error in errors)
2428 if (error.Code == TwitterErrorCode.InvalidToken ||
2429 error.Code == TwitterErrorCode.SuspendedAccount)
2431 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2435 throw new WebApiException("Err:" + string.Join(",", errors.Select(x => x.ToString())) + "(" + callerMethodName + ")", responseText);
2437 catch (SerializationException) { }
2439 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2442 public int GetTextLengthRemain(string postText)
2444 var matchDm = Twitter.DMSendTextRegex.Match(postText);
2445 if (matchDm.Success)
2446 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
2448 return this.GetTextLengthRemainInternal(postText, isDm: false);
2451 private int GetTextLengthRemainInternal(string postText, bool isDm)
2456 while (pos < postText.Length)
2460 if (char.IsSurrogatePair(postText, pos))
2461 pos += 2; // サロゲートペアの場合は2文字分進める
2466 var urls = TweetExtractor.ExtractUrls(postText);
2467 foreach (var url in urls)
2469 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
2470 ? this.Configuration.ShortUrlLengthHttps
2471 : this.Configuration.ShortUrlLength;
2473 textLength += shortUrlLength - url.Length;
2477 return this.Configuration.DmTextCharacterLimit - textLength;
2479 return 140 - textLength;
2483 #region "UserStream"
2484 private string trackWord_ = "";
2485 public string TrackWord
2496 private bool allAtReply_ = false;
2497 public bool AllAtReply
2505 allAtReply_ = value;
2509 public event EventHandler NewPostFromStream;
2510 public event EventHandler UserStreamStarted;
2511 public event EventHandler UserStreamStopped;
2512 public event EventHandler<PostDeletedEventArgs> PostDeleted;
2513 public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
2514 private DateTime _lastUserstreamDataReceived;
2515 private TwitterUserstream userStream;
2517 public class FormattedEvent
2519 public MyCommon.EVENTTYPE Eventtype { get; set; }
2520 public DateTime CreatedAt { get; set; }
2521 public string Event { get; set; }
2522 public string Username { get; set; }
2523 public string Target { get; set; }
2524 public Int64 Id { get; set; }
2525 public bool IsMe { get; set; }
2528 public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
2529 public List<FormattedEvent> StoredEvent
2533 return storedEvent_;
2537 storedEvent_ = value;
2541 private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
2543 ["favorite"] = MyCommon.EVENTTYPE.Favorite,
2544 ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
2545 ["follow"] = MyCommon.EVENTTYPE.Follow,
2546 ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
2547 ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
2548 ["block"] = MyCommon.EVENTTYPE.Block,
2549 ["unblock"] = MyCommon.EVENTTYPE.Unblock,
2550 ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
2551 ["deleted"] = MyCommon.EVENTTYPE.Deleted,
2552 ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
2553 ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
2554 ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
2555 ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
2556 ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
2557 ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
2558 ["mute"] = MyCommon.EVENTTYPE.Mute,
2559 ["unmute"] = MyCommon.EVENTTYPE.Unmute,
2560 ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
2563 public bool IsUserstreamDataReceived
2567 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
2571 private void userStream_StatusArrived(string line)
2573 this._lastUserstreamDataReceived = DateTime.Now;
2574 if (string.IsNullOrEmpty(line)) return;
2576 if (line.First() != '{' || line.Last() != '}')
2578 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
2586 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
2588 var xElm = XElement.Load(jsonReader);
2589 if (xElm.Element("friends") != null)
2591 Debug.WriteLine("friends");
2594 else if (xElm.Element("delete") != null)
2596 Debug.WriteLine("delete");
2599 if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
2602 long.TryParse(idElm.Value, out id);
2604 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2606 else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
2609 long.TryParse(idElm.Value, out id);
2611 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2615 MyCommon.TraceOut("delete:" + line);
2618 for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
2620 var sEvt = this.StoredEvent[i];
2621 if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
2623 this.StoredEvent.RemoveAt(i);
2628 else if (xElm.Element("limit") != null)
2630 Debug.WriteLine(line);
2633 else if (xElm.Element("event") != null)
2635 Debug.WriteLine("event: " + xElm.Element("event").Value);
2636 CreateEventFromJson(line);
2639 else if (xElm.Element("direct_message") != null)
2641 Debug.WriteLine("direct_message");
2644 else if (xElm.Element("retweeted_status") != null)
2646 var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
2647 var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
2649 // 自分に関係しないリツイートの場合は無視する
2650 var selfUserId = this.UserId.ToString();
2651 if (sourceUserId == selfUserId || targetUserId == selfUserId)
2653 // 公式 RT をイベントとしても扱う
2654 var evt = CreateEventFromRetweet(xElm);
2657 this.StoredEvent.Insert(0, evt);
2659 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2663 // 従来通り公式 RT の表示も行うため return しない
2665 else if (xElm.Element("scrub_geo") != null)
2669 TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
2670 long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
2674 MyCommon.TraceOut("scrub_geo:" + line);
2682 CreateDirectMessagesFromJson(line, MyCommon.WORKERTYPE.UserStream, false);
2686 CreatePostsFromJson("[" + line + "]", MyCommon.WORKERTYPE.Timeline, null, false);
2689 catch (WebApiException ex)
2691 MyCommon.TraceOut(ex);
2694 catch(NullReferenceException)
2696 MyCommon.TraceOut("NullRef StatusArrived: " + line);
2699 this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
2703 /// UserStreamsから受信した公式RTをイベントに変換します
2705 private FormattedEvent CreateEventFromRetweet(XElement xElm)
2707 return new FormattedEvent
2709 Eventtype = MyCommon.EVENTTYPE.Retweet,
2711 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
2712 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
2713 Username = xElm.XPathSelectElement("/user/screen_name").Value,
2714 Target = string.Format("@{0}:{1}", new[]
2716 xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
2717 WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
2719 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
2723 private void CreateEventFromJson(string content)
2725 TwitterStreamEvent eventData = null;
2728 eventData = TwitterStreamEvent.ParseJson(content);
2730 catch(SerializationException ex)
2732 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
2736 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
2739 var evt = new FormattedEvent();
2740 evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
2741 evt.Event = eventData.Event;
2742 evt.Username = eventData.Source.ScreenName;
2743 evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
2745 MyCommon.EVENTTYPE eventType;
2746 eventTable.TryGetValue(eventData.Event, out eventType);
2747 evt.Eventtype = eventType;
2749 TwitterStreamEvent<TwitterStatus> tweetEvent;
2751 switch (eventData.Event)
2753 case "access_revoked":
2754 case "access_unrevoked":
2756 case "user_suspend":
2759 if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
2761 if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
2765 return; //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
2770 evt.Target = "@" + eventData.Target.ScreenName;
2772 case "favorited_retweet":
2773 case "retweeted_retweet":
2777 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2778 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2779 evt.Id = tweetEvent.TargetObject.Id;
2781 if (SettingCommon.Instance.IsRemoveSameEvent)
2783 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2787 var tabinfo = TabInformations.GetInstance();
2790 var statusId = tweetEvent.TargetObject.Id;
2791 if (!tabinfo.Posts.TryGetValue(statusId, out post))
2794 if (eventData.Event == "favorite")
2796 var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2797 if (!favTab.Contains(post.StatusId))
2798 favTab.AddPostImmediately(post.StatusId, post.IsRead);
2800 if (tweetEvent.Source.Id == this.UserId)
2804 else if (tweetEvent.Target.Id == this.UserId)
2806 post.FavoritedCount++;
2808 if (SettingCommon.Instance.FavEventUnread)
2809 tabinfo.SetReadAllTab(post.StatusId, read: false);
2814 if (tweetEvent.Source.Id == this.UserId)
2818 else if (tweetEvent.Target.Id == this.UserId)
2820 post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2824 case "quoted_tweet":
2825 if (evt.IsMe) return;
2827 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2828 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2829 evt.Id = tweetEvent.TargetObject.Id;
2831 if (SettingCommon.Instance.IsRemoveSameEvent)
2833 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2837 case "list_member_added":
2838 case "list_member_removed":
2839 case "list_created":
2840 case "list_destroyed":
2841 case "list_updated":
2842 case "list_user_subscribed":
2843 case "list_user_unsubscribed":
2844 var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2845 evt.Target = listEvent.TargetObject.FullName;
2848 if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2852 if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2861 evt.Target = "@" + eventData.Target.ScreenName;
2862 if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2864 TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2868 evt.Target = "@" + eventData.Target.ScreenName;
2869 if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2871 TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2876 MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2879 this.StoredEvent.Insert(0, evt);
2881 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2884 private void userStream_Started()
2886 this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2889 private void userStream_Stopped()
2891 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2894 public bool UserStreamEnabled
2898 return userStream == null ? false : userStream.Enabled;
2902 public void StartUserStream()
2904 if (userStream != null)
2908 userStream = new TwitterUserstream(twCon);
2909 userStream.StatusArrived += userStream_StatusArrived;
2910 userStream.Started += userStream_Started;
2911 userStream.Stopped += userStream_Stopped;
2912 userStream.Start(this.AllAtReply, this.TrackWord);
2915 public void StopUserStream()
2917 userStream?.Dispose();
2919 if (!MyCommon._endingFlag)
2921 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2925 public void ReconnectUserStream()
2927 if (userStream != null)
2929 this.StartUserStream();
2933 private class TwitterUserstream : IDisposable
2935 public event Action<string> StatusArrived;
2936 public event Action Stopped;
2937 public event Action Started;
2938 private HttpTwitter twCon;
2940 private Thread _streamThread;
2941 private bool _streamActive;
2943 private bool _allAtreplies = false;
2944 private string _trackwords = "";
2946 public TwitterUserstream(HttpTwitter twitterConnection)
2948 twCon = (HttpTwitter)twitterConnection.Clone();
2951 public void Start(bool allAtReplies, string trackwords)
2953 this.AllAtReplies = allAtReplies;
2954 this.TrackWords = trackwords;
2955 _streamActive = true;
2956 if (_streamThread != null && _streamThread.IsAlive) return;
2957 _streamThread = new Thread(UserStreamLoop);
2958 _streamThread.Name = "UserStreamReceiver";
2959 _streamThread.IsBackground = true;
2960 _streamThread.Start();
2967 return _streamActive;
2971 public bool AllAtReplies
2975 return _allAtreplies;
2979 _allAtreplies = value;
2983 public string TrackWords
2991 _trackwords = value;
2995 private void UserStreamLoop()
3001 StreamReader sr = null;
3004 if (!MyCommon.IsNetworkAvailable())
3012 var res = twCon.UserStream(ref st, _allAtreplies, _trackwords, Networking.GetUserAgentString());
3016 case HttpStatusCode.OK:
3017 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
3019 case HttpStatusCode.Unauthorized:
3020 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
3028 //MyCommon.TraceOut("Stop:stream is null")
3032 sr = new StreamReader(st);
3034 while (_streamActive && !sr.EndOfStream && Twitter.AccountState == MyCommon.ACCOUNT_STATE.Valid)
3036 StatusArrived?.Invoke(sr.ReadLine());
3037 //this.LastTime = Now;
3040 if (sr.EndOfStream || Twitter.AccountState == MyCommon.ACCOUNT_STATE.Invalid)
3043 //MyCommon.TraceOut("Stop:EndOfStream")
3048 catch(WebException ex)
3050 if (ex.Status == WebExceptionStatus.Timeout)
3052 sleepSec = 30; //MyCommon.TraceOut("Stop:Timeout")
3054 else if (ex.Response != null && (int)((HttpWebResponse)ex.Response).StatusCode == 420)
3056 //MyCommon.TraceOut("Stop:Connection Limit")
3062 //MyCommon.TraceOut("Stop:WebException " + ex.Status.ToString())
3065 catch(ThreadAbortException)
3072 //MyCommon.TraceOut("Stop:IOException with Active." + Environment.NewLine + ex.Message)
3074 catch(ArgumentException ex)
3076 //System.ArgumentException: ストリームを読み取れませんでした。
3077 //サーバー側もしくは通信経路上で切断された場合?タイムアウト頻発後発生
3079 MyCommon.TraceOut(ex, "Stop:ArgumentException");
3083 MyCommon.TraceOut("Stop:Exception." + Environment.NewLine + ex.Message);
3084 MyCommon.ExceptionOut(ex);
3093 twCon.RequestAbort();
3098 while (_streamActive && ms < sleepSec * 1000)
3106 } while (this._streamActive);
3112 MyCommon.TraceOut("Stop:EndLoop");
3115 #region "IDisposable Support"
3116 private bool disposedValue; // 重複する呼び出しを検出するには
3119 protected virtual void Dispose(bool disposing)
3121 if (!this.disposedValue)
3125 _streamActive = false;
3126 if (_streamThread != null && _streamThread.IsAlive)
3128 _streamThread.Abort();
3132 this.disposedValue = true;
3135 //protected Overrides void Finalize()
3137 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3139 // MyBase.Finalize()
3142 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
3143 public void Dispose()
3145 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3147 GC.SuppressFinalize(this);
3154 #region "IDisposable Support"
3155 private bool disposedValue; // 重複する呼び出しを検出するには
3158 protected virtual void Dispose(bool disposing)
3160 if (!this.disposedValue)
3164 this.StopUserStream();
3167 this.disposedValue = true;
3170 //protected Overrides void Finalize()
3172 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3174 // MyBase.Finalize()
3177 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
3178 public void Dispose()
3180 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
3182 GC.SuppressFinalize(this);
3187 public class PostDeletedEventArgs : EventArgs
3189 public long StatusId { get; }
3191 public PostDeletedEventArgs(long statusId)
3193 this.StatusId = statusId;
3197 public class UserStreamEventReceivedEventArgs : EventArgs
3199 public Twitter.FormattedEvent EventData { get; }
3201 public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
3203 this.EventData = eventData;