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.Net.Http;
33 using System.Runtime.CompilerServices;
34 using System.Runtime.Serialization;
35 using System.Runtime.Serialization.Json;
37 using System.Text.RegularExpressions;
38 using System.Threading;
39 using System.Threading.Tasks;
42 using System.Xml.Linq;
43 using System.Xml.XPath;
45 using System.Reflection;
46 using System.Collections.Generic;
48 using System.Windows.Forms;
50 using OpenTween.Api.DataModel;
51 using OpenTween.Connection;
55 public class Twitter : IDisposable
57 #region Regexp from twitter-text-js
59 // The code in this region code block incorporates works covered by
60 // the following copyright and permission notices:
62 // Copyright 2011 Twitter, Inc.
64 // Licensed under the Apache License, Version 2.0 (the "License"); you
65 // may not use this work except in compliance with the License. You
66 // may obtain a copy of the License in the LICENSE file, or at:
68 // http://www.apache.org/licenses/LICENSE-2.0
70 // Unless required by applicable law or agreed to in writing, software
71 // distributed under the License is distributed on an "AS IS" BASIS,
72 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
73 // implied. See the License for the specific language governing
74 // permissions and limitations under the License.
77 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";
78 private const string NON_LATIN_HASHTAG_CHARS = @"\u0400-\u04ff\u0500-\u0527\u1100-\u11ff\u3130-\u3185\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF";
79 //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";
80 private const string CJ_HASHTAG_CHARACTERS = @"\u30A1-\u30FA\u30FC\u3005\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u309A\u3400-\u4DBF\p{IsCJKUnifiedIdeographs}";
81 private const string HASHTAG_BOUNDARY = @"^|$|\s|「|」|。|\.|!";
82 private const string HASHTAG_ALPHA = "[a-z_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
83 private const string HASHTAG_ALPHANUMERIC = "[a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
84 private const string HASHTAG_TERMINATOR = "[^a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
85 public const string HASHTAG = "(" + HASHTAG_BOUNDARY + ")(#|#)(" + HASHTAG_ALPHANUMERIC + "*" + HASHTAG_ALPHA + HASHTAG_ALPHANUMERIC + "*)(?=" + HASHTAG_TERMINATOR + "|" + HASHTAG_BOUNDARY + ")";
87 private const string url_valid_preceding_chars = @"(?:[^A-Za-z0-9@@$##\ufffe\ufeff\uffff\u202a-\u202e]|^)";
88 public const string url_invalid_without_protocol_preceding_chars = @"[-_./]$";
89 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";
90 private const string url_valid_domain_chars = @"[^" + url_invalid_domain_chars + "]";
91 private const string url_valid_subdomain = @"(?:(?:" + url_valid_domain_chars + @"(?:[_-]|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
92 private const string url_valid_domain_name = @"(?:(?:" + url_valid_domain_chars + @"(?:-|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
93 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]|$))";
94 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]|$))";
95 private const string url_valid_punycode = @"(?:xn--[0-9a-z]+)";
96 private const string url_valid_domain = @"(?<domain>" + url_valid_subdomain + "*" + url_valid_domain_name + "(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + ")|" + url_valid_punycode + ")";
97 public const string url_valid_ascii_domain = @"(?:(?:[a-z0-9" + LATIN_ACCENTS + @"]+)\.)+(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + "|" + url_valid_punycode + ")";
98 public const string url_invalid_short_domain = "^" + url_valid_domain_name + url_valid_CCTLD + "$";
99 private const string url_valid_port_number = @"[0-9]+";
101 private const string url_valid_general_path_chars = @"[a-z0-9!*';:=+,.$/%#\[\]\-_~|&" + LATIN_ACCENTS + "]";
102 private const string url_balance_parens = @"(?:\(" + url_valid_general_path_chars + @"+\))";
103 private const string url_valid_path_ending_chars = @"(?:[+\-a-z0-9=_#/" + LATIN_ACCENTS + "]|" + url_balance_parens + ")";
104 private const string pth = "(?:" +
106 url_valid_general_path_chars + "*" +
107 "(?:" + url_balance_parens + url_valid_general_path_chars + "*)*" +
108 url_valid_path_ending_chars +
109 ")|(?:@" + url_valid_general_path_chars + "+/)" +
111 private const string qry = @"(?<query>\?[a-z0-9!?*'();:&=+$/%#\[\]\-_.,~|]*[a-z0-9_&=#/])?";
112 public const string rgUrl = @"(?<before>" + url_valid_preceding_chars + ")" +
113 "(?<url>(?<protocol>https?://)?" +
114 "(?<domain>" + url_valid_domain + ")" +
115 "(?::" + url_valid_port_number + ")?" +
116 "(?<path>/" + pth + "*)?" +
123 /// Twitter API のステータスページのURL
125 public const string ServiceAvailabilityStatusUrl = "https://status.io.watchmouse.com/7617";
128 /// ツイートへのパーマリンクURLを判定する正規表現
130 public static readonly Regex StatusUrlRegex = new Regex(@"https?://([^.]+\.)?twitter\.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)/status(es)?/(?<StatusId>[0-9]+)(/photo)?", RegexOptions.IgnoreCase);
133 /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
135 public static readonly Regex ThirdPartyStatusUrlRegex = new Regex(@"https?://(?:[^.]+\.)?(?:
136 favstar\.fm/users/[a-zA-Z0-9_]+/status/ # Favstar
137 | favstar\.fm/t/ # Favstar (short)
138 | aclog\.koba789\.com/i/ # aclog
139 | frtrt\.net/solo_status\.php\?status= # RtRT
140 )(?<StatusId>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
143 /// DM送信かどうかを判定する正規表現
145 public static readonly Regex DMSendTextRegex = new Regex(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
147 public TwitterApi Api { get; }
148 public TwitterConfiguration Configuration { get; private set; }
150 delegate void GetIconImageDelegate(PostClass post);
151 private readonly object LockObj = new object();
152 private ISet<long> followerId = new HashSet<long>();
153 private bool _GetFollowerResult = false;
154 private long[] noRTId = new long[0];
155 private bool _GetNoRetweetResult = false;
158 private string _uname;
160 private bool _readOwnPost;
161 private List<string> _hashList = new List<string>();
163 //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
164 private long minHomeTimeline = long.MaxValue;
165 private long minMentions = long.MaxValue;
166 private long minDirectmessage = long.MaxValue;
167 private long minDirectmessageSent = long.MaxValue;
169 //private FavoriteQueue favQueue;
171 private HttpTwitter twCon = new HttpTwitter();
173 //private List<PostClass> _deletemessages = new List<PostClass>();
175 public Twitter() : this(new TwitterApi())
179 public Twitter(TwitterApi api)
182 this.Configuration = TwitterConfiguration.DefaultConfiguration();
185 public TwitterApiAccessLevel AccessLevel
189 return MyCommon.TwitterApiInfo.AccessLevel;
193 protected void ResetApiStatus()
195 MyCommon.TwitterApiInfo.Reset();
198 public void Authenticate(string username, string password)
200 this.ResetApiStatus();
206 res = twCon.AuthUserAndPass(username, password, ref content);
210 throw new WebApiException("Err:" + ex.Message, ex);
213 this.CheckStatusCode(res, content);
215 _uname = username.ToLowerInvariant();
216 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
219 public string StartAuthentication()
222 this.ResetApiStatus();
225 string pinPageUrl = null;
226 var res = twCon.AuthGetRequestToken(ref pinPageUrl);
228 throw new WebApiException("Err:Failed to access auth server.");
234 throw new WebApiException("Err:Failed to access auth server.", ex);
238 public void Authenticate(string pinCode)
240 this.ResetApiStatus();
245 res = twCon.AuthGetAccessToken(pinCode);
249 throw new WebApiException("Err:Failed to access auth acc server.", ex);
252 this.CheckStatusCode(res, null);
254 _uname = Username.ToLowerInvariant();
255 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
258 public void ClearAuthInfo()
260 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
261 this.ResetApiStatus();
262 twCon.ClearAuthInfo();
265 public void VerifyCredentials()
271 res = twCon.VerifyCredentials(ref content);
275 throw new WebApiException("Err:" + ex.Message, ex);
278 this.CheckStatusCode(res, content);
282 var user = TwitterUser.ParseJson(content);
284 this.twCon.AuthenticatedUserId = user.Id;
285 this.UpdateUserStats(user);
287 catch (SerializationException ex)
289 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
290 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
294 public void Initialize(string token, string tokenSecret, string username, long userId)
297 if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
299 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
301 this.ResetApiStatus();
302 this.Api.Initialize(token, tokenSecret, userId, username);
303 twCon.Initialize(token, tokenSecret, username, userId);
304 _uname = username.ToLowerInvariant();
305 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
308 public string PreProcessUrl(string orgData)
312 //var IDNConveter = new IdnMapping();
313 var href = "<a href=\"";
317 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
321 posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
322 posl1 += href.Length;
323 posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
324 urlStr = orgData.Substring(posl1, posl2 - posl1);
326 if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
327 && !urlStr.StartsWith("https://", StringComparison.Ordinal)
328 && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
333 var replacedUrl = MyCommon.IDNEncode(urlStr);
334 if (replacedUrl == null) continue;
335 if (replacedUrl == urlStr) continue;
337 orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
348 private string GetPlainText(string orgData)
350 return WebUtility.HtmlDecode(Regex.Replace(orgData, "(?<tagStart><a [^>]+>)(?<text>[^<]+)(?<tagEnd></a>)", "${text}"));
353 // htmlの簡易サニタイズ(詳細表示に不要なタグの除去)
355 private string SanitizeHtml(string orgdata)
357 var retdata = orgdata;
359 retdata = Regex.Replace(retdata, "<(script|object|applet|image|frameset|fieldset|legend|style).*" +
360 "</(script|object|applet|image|frameset|fieldset|legend|style)>", "", RegexOptions.IgnoreCase);
362 retdata = Regex.Replace(retdata, "<(frame|link|iframe|img)>", "", RegexOptions.IgnoreCase);
367 private string AdjustHtml(string orgData)
369 var retStr = orgData;
370 //var m = Regex.Match(retStr, "<a [^>]+>[#|#](?<1>[a-zA-Z0-9_]+)</a>");
375 // _hashList.Add("#" + m.Groups(1).Value);
379 retStr = Regex.Replace(retStr, "<a [^>]*href=\"/", "<a href=\"https://twitter.com/");
380 retStr = retStr.Replace("<a href=", "<a target=\"_self\" href=");
381 retStr = Regex.Replace(retStr, @"(\r\n?|\n)", "<br>"); // CRLF, CR, LF は全て <br> に置換する
383 //半角スペースを置換(Thanks @anis774)
387 ret = EscapeSpace(ref retStr);
390 return SanitizeHtml(retStr);
393 private bool EscapeSpace(ref string html)
395 //半角スペースを置換(Thanks @anis774)
397 for (int i = 0; i < html.Length; i++)
408 if ((!isTag) && (html[i] == ' '))
410 html = html.Remove(i, 1);
411 html = html.Insert(i, " ");
418 private struct PostInfo
420 public string CreatedAt;
423 public string UserId;
424 public PostInfo(string Created, string IdStr, string txt, string uid)
431 public bool Equals(PostInfo dst)
433 if (this.CreatedAt == dst.CreatedAt && this.Id == dst.Id && this.Text == dst.Text && this.UserId == dst.UserId)
444 static private PostInfo _prev = new PostInfo("", "", "", "");
445 private bool IsPostRestricted(TwitterStatus status)
447 var _current = new PostInfo("", "", "", "");
449 _current.CreatedAt = status.CreatedAt;
450 _current.Id = status.IdStr;
451 if (status.Text == null)
457 _current.Text = status.Text;
459 _current.UserId = status.User.IdStr;
461 if (_current.Equals(_prev))
465 _prev.CreatedAt = _current.CreatedAt;
466 _prev.Id = _current.Id;
467 _prev.Text = _current.Text;
468 _prev.UserId = _current.UserId;
473 public async Task PostStatus(string postStr, long? reply_to, IReadOnlyList<long> mediaIds = null)
475 this.CheckAccountState();
477 if (mediaIds == null &&
478 Twitter.DMSendTextRegex.IsMatch(postStr))
480 await this.SendDirectMessage(postStr)
481 .ConfigureAwait(false);
485 var response = await this.Api.StatusesUpdate(postStr, reply_to, mediaIds)
486 .ConfigureAwait(false);
488 var status = await response.LoadJsonAsync()
489 .ConfigureAwait(false);
491 this.UpdateUserStats(status.User);
493 if (IsPostRestricted(status))
495 throw new WebApiException("OK:Delaying?");
499 public async Task PostStatusWithMultipleMedia(string postStr, long? reply_to, IMediaItem[] mediaItems)
501 this.CheckAccountState();
503 if (Twitter.DMSendTextRegex.IsMatch(postStr))
505 await this.SendDirectMessage(postStr)
506 .ConfigureAwait(false);
510 if (mediaItems.Length == 0)
511 throw new WebApiException("Err:Invalid Files!");
513 var uploadTasks = from m in mediaItems
514 select this.UploadMedia(m);
516 var mediaIds = await Task.WhenAll(uploadTasks)
517 .ConfigureAwait(false);
519 await this.PostStatus(postStr, reply_to, mediaIds)
520 .ConfigureAwait(false);
523 public async Task<long> UploadMedia(IMediaItem item)
525 this.CheckAccountState();
527 var response = await this.Api.MediaUpload(item)
528 .ConfigureAwait(false);
530 var media = await response.LoadJsonAsync()
531 .ConfigureAwait(false);
533 return media.MediaId;
536 public async Task SendDirectMessage(string postStr)
538 this.CheckAccountState();
539 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
541 var mc = Twitter.DMSendTextRegex.Match(postStr);
543 var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
544 .ConfigureAwait(false);
546 var dm = await response.LoadJsonAsync()
547 .ConfigureAwait(false);
549 this.UpdateUserStats(dm.Sender);
552 public async Task PostRetweet(long id, bool read)
554 this.CheckAccountState();
558 var post = TabInformations.GetInstance()[id];
561 throw new WebApiException("Err:Target isn't found.");
563 if (TabInformations.GetInstance()[id].RetweetedId != null)
565 target = TabInformations.GetInstance()[id].RetweetedId.Value; //再RTの場合は元発言をRT
568 var response = await this.Api.StatusesRetweet(target)
569 .ConfigureAwait(false);
571 var status = await response.LoadJsonAsync()
572 .ConfigureAwait(false);
575 post = CreatePostsFromStatusData(status);
577 throw new WebApiException("Invalid Json!");
582 if (TabInformations.GetInstance().ContainsKey(post.StatusId))
586 if (post.RetweetedId == null)
587 throw new WebApiException("Invalid Json!");
593 if (_readOwnPost) post.IsRead = true;
596 TabInformations.GetInstance().AddPost(post);
599 public string Username
603 return twCon.AuthenticatedUsername;
611 return twCon.AuthenticatedUserId;
615 public string Password
619 return twCon.Password;
623 private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
624 public static MyCommon.ACCOUNT_STATE AccountState
628 return _accountState;
632 _accountState = value;
636 public bool RestrictFavCheck { get; set; }
639 public void GetTweenBinary(string strVer)
644 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/Tween" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
645 Path.Combine(MyCommon.settingPath, "TweenNew.exe")))
647 throw new WebApiException("Err:Download failed");
650 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, "en")))
652 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, "en"));
654 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenResEn" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
655 Path.Combine(Path.Combine(MyCommon.settingPath, "en"), "Tween.resourcesNew.dll")))
657 throw new WebApiException("Err:Download failed");
659 //その他言語圏のリソース。取得失敗しても継続
662 if (!Thread.CurrentThread.CurrentUICulture.IsNeutralCulture)
664 var idx = Thread.CurrentThread.CurrentUICulture.Name.LastIndexOf('-');
667 curCul = Thread.CurrentThread.CurrentUICulture.Name.Substring(0, idx);
671 curCul = Thread.CurrentThread.CurrentUICulture.Name;
676 curCul = Thread.CurrentThread.CurrentUICulture.Name;
678 if (!string.IsNullOrEmpty(curCul) && curCul != "en" && curCul != "ja")
680 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul)))
682 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul));
684 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
685 Path.Combine(Path.Combine(MyCommon.settingPath, curCul), "Tween.resourcesNew.dll")))
687 //return "Err:Download failed";
692 if (!Thread.CurrentThread.CurrentCulture.IsNeutralCulture)
694 var idx = Thread.CurrentThread.CurrentCulture.Name.LastIndexOf('-');
697 curCul2 = Thread.CurrentThread.CurrentCulture.Name.Substring(0, idx);
701 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
706 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
708 if (!string.IsNullOrEmpty(curCul2) && curCul2 != "en" && curCul2 != curCul)
710 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul2)))
712 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul2));
714 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul2 + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
715 Path.Combine(Path.Combine(MyCommon.settingPath, curCul2), "Tween.resourcesNew.dll")))
717 //return "Err:Download failed";
722 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenUp3.gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
723 Path.Combine(MyCommon.settingPath, "TweenUp3.exe")))
725 throw new WebApiException("Err:Download failed");
728 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenDll" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
729 Path.Combine(MyCommon.settingPath, "TweenNew.XmlSerializers.dll")))
731 throw new WebApiException("Err:Download failed");
736 throw new WebApiException("Err:Download failed", ex);
741 public bool ReadOwnPost
749 _readOwnPost = value;
753 public int FollowersCount { get; private set; }
754 public int FriendsCount { get; private set; }
755 public int StatusesCount { get; private set; }
756 public string Location { get; private set; } = "";
757 public string Bio { get; private set; } = "";
759 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
760 private void UpdateUserStats(TwitterUser self)
762 this.FollowersCount = self.FollowersCount;
763 this.FriendsCount = self.FriendsCount;
764 this.StatusesCount = self.StatusesCount;
765 this.Location = self.Location;
766 this.Bio = self.Description;
770 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
772 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
774 return count >= 20 && count <= GetMaxApiResultCount(type);
778 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
780 public static bool VerifyMoreApiResultCount(int count)
782 return count >= 20 && count <= 200;
786 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
788 public static bool VerifyFirstApiResultCount(int count)
790 return count >= 20 && count <= 200;
794 /// WORKERTYPEに応じた取得可能な最大件数を取得する
796 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
798 // 参照: REST APIs - 各endpointのcountパラメータ
799 // https://dev.twitter.com/rest/public
802 case MyCommon.WORKERTYPE.Timeline:
803 case MyCommon.WORKERTYPE.Reply:
804 case MyCommon.WORKERTYPE.UserTimeline:
805 case MyCommon.WORKERTYPE.Favorites:
806 case MyCommon.WORKERTYPE.DirectMessegeRcv:
807 case MyCommon.WORKERTYPE.DirectMessegeSnt:
808 case MyCommon.WORKERTYPE.List: // 不明
811 case MyCommon.WORKERTYPE.PublicSearch:
815 throw new InvalidOperationException("Invalid type: " + type);
820 /// WORKERTYPEに応じた取得件数を取得する
822 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
824 if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
825 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
830 if (SettingCommon.Instance.UseAdditionalCount)
834 case MyCommon.WORKERTYPE.Favorites:
835 if (SettingCommon.Instance.FavoritesCountApi != 0)
836 return SettingCommon.Instance.FavoritesCountApi;
838 case MyCommon.WORKERTYPE.List:
839 if (SettingCommon.Instance.ListCountApi != 0)
840 return SettingCommon.Instance.ListCountApi;
842 case MyCommon.WORKERTYPE.PublicSearch:
843 if (SettingCommon.Instance.SearchCountApi != 0)
844 return SettingCommon.Instance.SearchCountApi;
846 case MyCommon.WORKERTYPE.UserTimeline:
847 if (SettingCommon.Instance.UserTimelineCountApi != 0)
848 return SettingCommon.Instance.UserTimelineCountApi;
851 if (more && SettingCommon.Instance.MoreCountApi != 0)
853 return Math.Min(SettingCommon.Instance.MoreCountApi, GetMaxApiResultCount(type));
855 if (startup && SettingCommon.Instance.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
857 return Math.Min(SettingCommon.Instance.FirstCountApi, GetMaxApiResultCount(type));
862 var count = SettingCommon.Instance.CountApi;
864 if (type == MyCommon.WORKERTYPE.Reply)
865 count = SettingCommon.Instance.CountApiReply;
867 return Math.Min(count, GetMaxApiResultCount(type));
870 public async Task GetTimelineApi(bool read, MyCommon.WORKERTYPE gType, bool more, bool startup)
872 this.CheckAccountState();
874 var count = GetApiResultCount(gType, more, startup);
876 TwitterStatus[] statuses;
877 if (gType == MyCommon.WORKERTYPE.Timeline)
881 statuses = await this.Api.StatusesHomeTimeline(count, maxId: this.minHomeTimeline)
882 .ConfigureAwait(false);
886 statuses = await this.Api.StatusesHomeTimeline(count)
887 .ConfigureAwait(false);
894 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: this.minMentions)
895 .ConfigureAwait(false);
899 statuses = await this.Api.StatusesMentionsTimeline(count)
900 .ConfigureAwait(false);
904 var minimumId = CreatePostsFromJson(statuses, gType, null, read);
906 if (minimumId != null)
908 if (gType == MyCommon.WORKERTYPE.Timeline)
909 this.minHomeTimeline = minimumId.Value;
911 this.minMentions = minimumId.Value;
915 public async Task GetUserTimelineApi(bool read, string userName, TabClass tab, bool more)
917 this.CheckAccountState();
919 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
921 TwitterStatus[] statuses;
922 if (string.IsNullOrEmpty(userName))
924 var target = tab.User;
925 if (string.IsNullOrEmpty(target)) return;
927 statuses = await this.Api.StatusesUserTimeline(userName, count)
928 .ConfigureAwait(false);
934 statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
935 .ConfigureAwait(false);
939 statuses = await this.Api.StatusesUserTimeline(userName, count)
940 .ConfigureAwait(false);
944 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
946 if (minimumId != null)
947 tab.OldestId = minimumId.Value;
950 public async Task<PostClass> GetStatusApi(bool read, long id)
952 this.CheckAccountState();
954 var status = await this.Api.StatusesShow(id)
955 .ConfigureAwait(false);
957 var item = CreatePostsFromStatusData(status);
959 throw new WebApiException("Err:Can't create post");
962 if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
967 public async Task GetStatusApi(bool read, long id, TabClass tab)
969 var post = await this.GetStatusApi(read, id)
970 .ConfigureAwait(false);
972 //非同期アイコン取得&StatusDictionaryに追加
973 if (tab != null && tab.IsInnerStorageTabType)
974 tab.AddPostToInnerStorage(post);
976 TabInformations.GetInstance().AddPost(post);
979 private PostClass CreatePostsFromStatusData(TwitterStatus status)
981 return CreatePostsFromStatusData(status, false);
984 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
986 var post = new PostClass();
987 TwitterEntities entities;
990 post.StatusId = status.Id;
991 if (status.RetweetedStatus != null)
993 var retweeted = status.RetweetedStatus;
995 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
998 post.RetweetedId = retweeted.Id;
1000 post.TextFromApi = retweeted.Text;
1001 entities = retweeted.MergedEntities;
1002 sourceHtml = retweeted.Source;
1004 post.InReplyToStatusId = retweeted.InReplyToStatusId;
1005 post.InReplyToUser = retweeted.InReplyToScreenName;
1006 post.InReplyToUserId = status.InReplyToUserId;
1015 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1016 post.IsFav = tc.Contains(retweeted.Id);
1019 if (retweeted.Coordinates != null)
1020 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
1023 var user = retweeted.User;
1025 if (user == null || user.ScreenName == null || status.User.ScreenName == null) return null;
1027 post.UserId = user.Id;
1028 post.ScreenName = user.ScreenName;
1029 post.Nickname = user.Name.Trim();
1030 post.ImageUrl = user.ProfileImageUrlHttps;
1031 post.IsProtect = user.Protected;
1034 post.RetweetedBy = status.User.ScreenName;
1035 post.RetweetedByUserId = status.User.Id;
1036 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
1040 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
1042 post.TextFromApi = status.Text;
1043 entities = status.MergedEntities;
1044 sourceHtml = status.Source;
1045 post.InReplyToStatusId = status.InReplyToStatusId;
1046 post.InReplyToUser = status.InReplyToScreenName;
1047 post.InReplyToUserId = status.InReplyToUserId;
1056 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1057 post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
1060 if (status.Coordinates != null)
1061 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
1064 var user = status.User;
1066 if (user == null || user.ScreenName == null) return null;
1068 post.UserId = user.Id;
1069 post.ScreenName = user.ScreenName;
1070 post.Nickname = user.Name.Trim();
1071 post.ImageUrl = user.ProfileImageUrlHttps;
1072 post.IsProtect = user.Protected;
1073 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
1076 string textFromApi = post.TextFromApi;
1077 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
1078 post.TextFromApi = textFromApi;
1079 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
1080 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1081 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1083 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
1084 .Where(x => x != post.StatusId && x != post.RetweetedId)
1085 .Distinct().ToArray();
1087 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
1088 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1092 var source = ParseSource(sourceHtml);
1093 post.Source = source.Item1;
1094 post.SourceUri = source.Item2;
1096 post.IsReply = post.ReplyToList.Contains(_uname);
1097 post.IsExcludeReply = false;
1105 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
1113 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
1115 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
1117 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
1119 return GetQuoteTweetStatusIds(urls);
1122 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
1124 foreach (var url in urls)
1126 var match = Twitter.StatusUrlRegex.Match(url);
1130 if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
1131 yield return statusId;
1136 private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabClass tab, bool read)
1138 long? minimumId = null;
1140 foreach (var status in items)
1142 PostClass post = null;
1143 post = CreatePostsFromStatusData(status);
1144 if (post == null) continue;
1146 if (minimumId == null || minimumId.Value > post.StatusId)
1147 minimumId = post.StatusId;
1154 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1158 if (tab.Contains(post.StatusId)) continue;
1163 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
1164 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
1167 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1169 //非同期アイコン取得&StatusDictionaryに追加
1170 if (tab != null && tab.IsInnerStorageTabType)
1171 tab.AddPostToInnerStorage(post);
1173 TabInformations.GetInstance().AddPost(post);
1179 private long? CreatePostsFromSearchJson(string content, TabClass tab, bool read, int count, bool more)
1181 TwitterSearchResult items;
1184 items = TwitterSearchResult.ParseJson(content);
1186 catch (SerializationException ex)
1188 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1189 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1191 catch (Exception ex)
1193 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1194 throw new WebApiException("Invalid Json!", content, ex);
1197 long? minimumId = null;
1199 foreach (var result in items.Statuses)
1201 var post = CreatePostsFromStatusData(result);
1205 if (minimumId == null || minimumId.Value > post.StatusId)
1206 minimumId = post.StatusId;
1208 if (!more && post.StatusId > tab.SinceId) tab.SinceId = post.StatusId;
1214 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1218 if (tab.Contains(post.StatusId)) continue;
1223 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
1225 //非同期アイコン取得&StatusDictionaryに追加
1226 if (tab != null && tab.IsInnerStorageTabType)
1227 tab.AddPostToInnerStorage(post);
1229 TabInformations.GetInstance().AddPost(post);
1235 private void CreateFavoritePostsFromJson(string content, bool read)
1237 TwitterStatus[] item;
1240 item = TwitterStatus.ParseJsonArray(content);
1242 catch (SerializationException ex)
1244 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1245 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1247 catch (Exception ex)
1249 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1250 throw new WebApiException("Invalid Json!", content, ex);
1253 var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1255 foreach (var status in item)
1260 if (favTab.Contains(status.Id)) continue;
1263 var post = CreatePostsFromStatusData(status, true);
1264 if (post == null) continue;
1268 TabInformations.GetInstance().AddPost(post);
1272 public async Task GetListStatus(bool read, TabClass tab, bool more, bool startup)
1274 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
1276 TwitterStatus[] statuses;
1279 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
1280 .ConfigureAwait(false);
1284 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
1285 .ConfigureAwait(false);
1288 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
1290 if (minimumId != null)
1291 tab.OldestId = minimumId.Value;
1295 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1297 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1298 internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1300 if (!posts.ContainsKey(startStatusId))
1301 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1303 var nextPost = posts[startStatusId];
1304 while (nextPost.InReplyToStatusId != null)
1306 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1308 nextPost = posts[nextPost.InReplyToStatusId.Value];
1314 public async Task GetRelatedResult(bool read, TabClass tab)
1316 var relPosts = new Dictionary<Int64, PostClass>();
1317 if (tab.RelationTargetPost.TextFromApi.Contains("@") && tab.RelationTargetPost.InReplyToStatusId == null)
1320 var p = TabInformations.GetInstance()[tab.RelationTargetPost.StatusId];
1321 if (p != null && p.InReplyToStatusId != null)
1323 tab.RelationTargetPost = p;
1327 p = await this.GetStatusApi(read, tab.RelationTargetPost.StatusId)
1328 .ConfigureAwait(false);
1329 tab.RelationTargetPost = p;
1332 relPosts.Add(tab.RelationTargetPost.StatusId, tab.RelationTargetPost);
1334 Exception lastException = null;
1336 // in_reply_to_status_id を使用してリプライチェインを辿る
1337 var nextPost = FindTopOfReplyChain(relPosts, tab.RelationTargetPost.StatusId);
1339 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1341 var inReplyToId = nextPost.InReplyToStatusId.Value;
1343 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1344 if (inReplyToPost == null)
1348 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1349 .ConfigureAwait(false);
1351 catch (WebApiException ex)
1358 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1360 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1363 //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1364 var text = tab.RelationTargetPost.Text;
1365 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1366 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1367 foreach (var _match in ma)
1370 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1372 if (relPosts.ContainsKey(_statusId))
1375 var p = TabInformations.GetInstance()[_statusId];
1380 p = await this.GetStatusApi(read, _statusId)
1381 .ConfigureAwait(false);
1383 catch (WebApiException ex)
1391 relPosts.Add(p.StatusId, p);
1395 relPosts.Values.ToList().ForEach(p =>
1397 if (p.IsMe && !read && this._readOwnPost)
1402 tab.AddPostToInnerStorage(p);
1405 if (lastException != null)
1406 throw new WebApiException(lastException.Message, lastException);
1409 public void GetSearch(bool read,
1415 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1417 long? sinceId = null;
1420 maxId = tab.OldestId - 1;
1424 sinceId = tab.SinceId;
1429 // TODO:一時的に40>100件に 件数変更UI作成の必要あり
1430 res = twCon.Search(tab.SearchWords, tab.SearchLang, count, maxId, sinceId, ref content);
1434 throw new WebApiException("Err:" + ex.Message, ex);
1438 case HttpStatusCode.BadRequest:
1439 throw new WebApiException("Invalid query", content);
1440 case HttpStatusCode.NotFound:
1441 throw new WebApiException("Invalid query", content);
1442 case HttpStatusCode.PaymentRequired: //API Documentには420と書いてあるが、該当コードがないので402にしてある
1443 throw new WebApiException("Search API Limit?", content);
1444 case HttpStatusCode.OK:
1447 throw new WebApiException("Err:" + res.ToString() + "(" + MethodBase.GetCurrentMethod().Name + ")", content);
1450 if (!TabInformations.GetInstance().ContainsTab(tab))
1453 var minimumId = this.CreatePostsFromSearchJson(content, tab, read, count, more);
1455 if (minimumId != null)
1456 tab.OldestId = minimumId.Value;
1459 private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read)
1461 foreach (var message in item)
1463 var post = new PostClass();
1466 post.StatusId = message.Id;
1467 if (gType != MyCommon.WORKERTYPE.UserStream)
1469 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1471 if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1475 if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1482 if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1486 post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1488 var textFromApi = message.Text;
1490 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
1491 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
1492 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1493 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1496 post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
1498 post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1499 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1504 if (gType == MyCommon.WORKERTYPE.UserStream)
1506 if (twCon.AuthenticatedUsername.Equals(message.Recipient.ScreenName, StringComparison.CurrentCultureIgnoreCase))
1508 user = message.Sender;
1514 user = message.Recipient;
1521 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1523 user = message.Sender;
1529 user = message.Recipient;
1535 post.UserId = user.Id;
1536 post.ScreenName = user.ScreenName;
1537 post.Nickname = user.Name.Trim();
1538 post.ImageUrl = user.ProfileImageUrlHttps;
1539 post.IsProtect = user.Protected;
1543 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name);
1544 MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1549 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1550 post.IsReply = false;
1551 post.IsExcludeReply = false;
1554 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1555 dmTab.AddPostToInnerStorage(post);
1559 public async Task GetDirectMessageApi(bool read, MyCommon.WORKERTYPE gType, bool more)
1561 this.CheckAccountState();
1562 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1564 var count = GetApiResultCount(gType, more, false);
1566 TwitterDirectMessage[] messages;
1567 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1571 messages = await this.Api.DirectMessagesRecv(count, maxId: this.minDirectmessage)
1572 .ConfigureAwait(false);
1576 messages = await this.Api.DirectMessagesRecv(count)
1577 .ConfigureAwait(false);
1584 messages = await this.Api.DirectMessagesSent(count, maxId: this.minDirectmessageSent)
1585 .ConfigureAwait(false);
1589 messages = await this.Api.DirectMessagesSent(count)
1590 .ConfigureAwait(false);
1594 CreateDirectMessagesFromJson(messages, gType, read);
1597 public void GetFavoritesApi(bool read,
1600 this.CheckAccountState();
1604 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
1608 res = twCon.Favorites(count, ref content);
1612 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1615 this.CheckStatusCode(res, content);
1617 CreateFavoritePostsFromJson(content, read);
1620 private string ReplaceTextFromApi(string text, TwitterEntities entities)
1622 if (entities != null)
1624 if (entities.Urls != null)
1626 foreach (var m in entities.Urls)
1628 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1631 if (entities.Media != null)
1633 foreach (var m in entities.Media)
1635 if (m.AltText != null)
1637 text = text.Replace(m.Url, string.Format(Properties.Resources.ImageAltText, m.AltText));
1641 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1652 /// <exception cref="WebApiException"/>
1653 public async Task RefreshFollowerIds()
1655 if (MyCommon._endingFlag) return;
1658 var newFollowerIds = new HashSet<long>();
1661 var ret = await this.Api.FollowersIds(cursor)
1662 .ConfigureAwait(false);
1664 if (ret.Ids == null)
1665 throw new WebApiException("ret.ids == null");
1667 newFollowerIds.UnionWith(ret.Ids);
1668 cursor = ret.NextCursor;
1669 } while (cursor != 0);
1671 this.followerId = newFollowerIds;
1672 TabInformations.GetInstance().RefreshOwl(this.followerId);
1674 this._GetFollowerResult = true;
1677 public bool GetFollowersSuccess
1681 return _GetFollowerResult;
1686 /// RT 非表示ユーザーを更新します
1688 /// <exception cref="WebApiException"/>
1689 public async Task RefreshNoRetweetIds()
1691 if (MyCommon._endingFlag) return;
1693 this.noRTId = await this.Api.NoRetweetIds()
1694 .ConfigureAwait(false);
1696 this._GetNoRetweetResult = true;
1699 public bool GetNoRetweetSuccess
1703 return _GetNoRetweetResult;
1708 /// t.co の文字列長などの設定情報を更新します
1710 /// <exception cref="WebApiException"/>
1711 public async Task RefreshConfiguration()
1713 this.Configuration = await this.Api.Configuration()
1714 .ConfigureAwait(false);
1717 public void GetListsApi()
1719 this.CheckAccountState();
1722 IEnumerable<ListElement> lists;
1727 res = twCon.GetLists(this.Username, ref content);
1729 catch (Exception ex)
1731 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1734 this.CheckStatusCode(res, content);
1738 lists = TwitterList.ParseJsonArray(content)
1739 .Select(x => new ListElement(x, this));
1741 catch (SerializationException ex)
1743 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1744 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1746 catch (Exception ex)
1748 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1749 throw new WebApiException("Err:Invalid Json!", content, ex);
1754 res = twCon.GetListsSubscriptions(this.Username, ref content);
1756 catch (Exception ex)
1758 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1761 this.CheckStatusCode(res, content);
1765 lists = lists.Concat(TwitterList.ParseJsonArray(content)
1766 .Select(x => new ListElement(x, this)));
1768 catch (SerializationException ex)
1770 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1771 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1773 catch (Exception ex)
1775 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1776 throw new WebApiException("Err:Invalid Json!", content, ex);
1779 TabInformations.GetInstance().SubscribableLists = lists.ToList();
1782 public void DeleteList(string list_id)
1789 res = twCon.DeleteListID(this.Username, list_id, ref content);
1793 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1796 this.CheckStatusCode(res, content);
1799 public ListElement EditList(string list_id, string new_name, bool isPrivate, string description)
1806 res = twCon.UpdateListID(this.Username, list_id, new_name, isPrivate, description, ref content);
1810 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1813 this.CheckStatusCode(res, content);
1817 var le = TwitterList.ParseJson(content);
1818 return new ListElement(le, this);
1820 catch(SerializationException ex)
1822 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1823 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1827 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1828 throw new WebApiException("Err:Invalid Json!", content, ex);
1832 public long GetListMembers(string list_id, List<UserInfo> lists, long cursor)
1834 this.CheckAccountState();
1840 res = twCon.GetListMembers(this.Username, list_id, cursor, ref content);
1844 throw new WebApiException("Err:" + ex.Message);
1847 this.CheckStatusCode(res, content);
1851 var users = TwitterUsers.ParseJson(content);
1852 Array.ForEach<TwitterUser>(
1854 u => lists.Add(new UserInfo(u)));
1856 return users.NextCursor;
1858 catch(SerializationException ex)
1860 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1861 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1865 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1866 throw new WebApiException("Err:Invalid Json!", content, ex);
1870 public void CreateListApi(string listName, bool isPrivate, string description)
1872 this.CheckAccountState();
1878 res = twCon.CreateLists(listName, isPrivate, description, ref content);
1882 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1885 this.CheckStatusCode(res, content);
1889 var le = TwitterList.ParseJson(content);
1890 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(le, this));
1892 catch(SerializationException ex)
1894 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1895 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1899 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1900 throw new WebApiException("Err:Invalid Json!", content, ex);
1904 public bool ContainsUserAtList(string listId, string user)
1906 this.CheckAccountState();
1913 res = this.twCon.ShowListMember(listId, user, ref content);
1917 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1920 if (res == HttpStatusCode.NotFound)
1925 this.CheckStatusCode(res, content);
1929 TwitterUser.ParseJson(content);
1938 public void AddUserToList(string listId, string user)
1945 res = twCon.CreateListMembers(listId, user, ref content);
1949 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1952 this.CheckStatusCode(res, content);
1955 public void RemoveUserToList(string listId, string user)
1962 res = twCon.DeleteListMembers(listId, user, ref content);
1966 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1969 this.CheckStatusCode(res, content);
1972 public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
1974 if (entities != null)
1976 if (entities.Hashtags != null)
1980 this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1983 if (entities.UserMentions != null)
1985 foreach (var ent in entities.UserMentions)
1987 var screenName = ent.ScreenName.ToLowerInvariant();
1988 if (!AtList.Contains(screenName))
1989 AtList.Add(screenName);
1992 if (entities.Media != null)
1996 foreach (var ent in entities.Media)
1998 if (!media.Any(x => x.Url == ent.MediaUrl))
2000 if (ent.VideoInfo != null &&
2001 ent.Type == "animated_gif" || ent.Type == "video")
2003 //var videoUrl = ent.VideoInfo.Variants
2004 // .Where(v => v.ContentType == "video/mp4")
2005 // .OrderByDescending(v => v.Bitrate)
2006 // .Select(v => v.Url).FirstOrDefault();
2007 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, ent.ExpandedUrl));
2010 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, videoUrl: null));
2017 // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
2018 text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
2020 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>");
2021 text = PreProcessUrl(text); //IDN置換
2026 private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
2029 /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
2031 public static Tuple<string, Uri> ParseSource(string sourceHtml)
2033 if (string.IsNullOrEmpty(sourceHtml))
2034 return Tuple.Create<string, Uri>("", null);
2039 // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
2041 var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
2044 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
2047 var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
2048 sourceUri = new Uri(SourceUriBase, uriStr);
2050 catch (UriFormatException)
2057 sourceText = WebUtility.HtmlDecode(sourceHtml);
2061 return Tuple.Create(sourceText, sourceUri);
2064 public TwitterApiStatus GetInfoApi()
2066 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
2068 if (MyCommon._endingFlag) return null;
2074 res = twCon.RateLimitStatus(ref content);
2078 this.ResetApiStatus();
2082 this.CheckStatusCode(res, content);
2086 MyCommon.TwitterApiInfo.UpdateFromJson(content);
2087 return MyCommon.TwitterApiInfo;
2089 catch (Exception ex)
2091 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
2092 MyCommon.TwitterApiInfo.Reset();
2098 /// ブロック中のユーザーを更新します
2100 /// <exception cref="WebApiException"/>
2101 public async Task RefreshBlockIds()
2103 if (MyCommon._endingFlag) return;
2106 var newBlockIds = new HashSet<long>();
2109 var ret = await this.Api.BlocksIds(cursor)
2110 .ConfigureAwait(false);
2112 newBlockIds.UnionWith(ret.Ids);
2113 cursor = ret.NextCursor;
2114 } while (cursor != 0);
2116 newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
2118 TabInformations.GetInstance().BlockIds = newBlockIds;
2122 /// ミュート中のユーザーIDを更新します
2124 /// <exception cref="WebApiException"/>
2125 public async Task RefreshMuteUserIdsAsync()
2127 if (MyCommon._endingFlag) return;
2129 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
2130 .ConfigureAwait(false);
2132 TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
2135 public string[] GetHashList()
2140 hashArray = _hashList.ToArray();
2146 public string AccessToken
2150 return twCon.AccessToken;
2154 public string AccessTokenSecret
2158 return twCon.AccessTokenSecret;
2162 private void CheckAccountState()
2164 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
2165 throw new WebApiException("Auth error. Check your account");
2168 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
2170 if (!this.AccessLevel.HasFlag(accessLevelFlags))
2171 throw new WebApiException("Auth Err:try to re-authorization.");
2174 private void CheckStatusCode(HttpStatusCode httpStatus, string responseText,
2175 [CallerMemberName] string callerMethodName = "")
2177 if (httpStatus == HttpStatusCode.OK)
2179 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2183 if (string.IsNullOrWhiteSpace(responseText))
2185 if (httpStatus == HttpStatusCode.Unauthorized)
2186 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2188 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")");
2193 var errors = TwitterError.ParseJson(responseText).Errors;
2194 if (errors == null || !errors.Any())
2196 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2199 foreach (var error in errors)
2201 if (error.Code == TwitterErrorCode.InvalidToken ||
2202 error.Code == TwitterErrorCode.SuspendedAccount)
2204 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2208 throw new WebApiException("Err:" + string.Join(",", errors.Select(x => x.ToString())) + "(" + callerMethodName + ")", responseText);
2210 catch (SerializationException) { }
2212 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2215 public int GetTextLengthRemain(string postText)
2217 var matchDm = Twitter.DMSendTextRegex.Match(postText);
2218 if (matchDm.Success)
2219 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
2221 return this.GetTextLengthRemainInternal(postText, isDm: false);
2224 private int GetTextLengthRemainInternal(string postText, bool isDm)
2229 while (pos < postText.Length)
2233 if (char.IsSurrogatePair(postText, pos))
2234 pos += 2; // サロゲートペアの場合は2文字分進める
2239 var urls = TweetExtractor.ExtractUrls(postText);
2240 foreach (var url in urls)
2242 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
2243 ? this.Configuration.ShortUrlLengthHttps
2244 : this.Configuration.ShortUrlLength;
2246 textLength += shortUrlLength - url.Length;
2250 return this.Configuration.DmTextCharacterLimit - textLength;
2252 return 140 - textLength;
2256 #region "UserStream"
2257 private string trackWord_ = "";
2258 public string TrackWord
2269 private bool allAtReply_ = false;
2270 public bool AllAtReply
2278 allAtReply_ = value;
2282 public event EventHandler NewPostFromStream;
2283 public event EventHandler UserStreamStarted;
2284 public event EventHandler UserStreamStopped;
2285 public event EventHandler<PostDeletedEventArgs> PostDeleted;
2286 public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
2287 private DateTime _lastUserstreamDataReceived;
2288 private TwitterUserstream userStream;
2290 public class FormattedEvent
2292 public MyCommon.EVENTTYPE Eventtype { get; set; }
2293 public DateTime CreatedAt { get; set; }
2294 public string Event { get; set; }
2295 public string Username { get; set; }
2296 public string Target { get; set; }
2297 public Int64 Id { get; set; }
2298 public bool IsMe { get; set; }
2301 public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
2302 public List<FormattedEvent> StoredEvent
2306 return storedEvent_;
2310 storedEvent_ = value;
2314 private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
2316 ["favorite"] = MyCommon.EVENTTYPE.Favorite,
2317 ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
2318 ["follow"] = MyCommon.EVENTTYPE.Follow,
2319 ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
2320 ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
2321 ["block"] = MyCommon.EVENTTYPE.Block,
2322 ["unblock"] = MyCommon.EVENTTYPE.Unblock,
2323 ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
2324 ["deleted"] = MyCommon.EVENTTYPE.Deleted,
2325 ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
2326 ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
2327 ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
2328 ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
2329 ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
2330 ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
2331 ["mute"] = MyCommon.EVENTTYPE.Mute,
2332 ["unmute"] = MyCommon.EVENTTYPE.Unmute,
2333 ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
2336 public bool IsUserstreamDataReceived
2340 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
2344 private void userStream_StatusArrived(string line)
2346 this._lastUserstreamDataReceived = DateTime.Now;
2347 if (string.IsNullOrEmpty(line)) return;
2349 if (line.First() != '{' || line.Last() != '}')
2351 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
2359 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
2361 var xElm = XElement.Load(jsonReader);
2362 if (xElm.Element("friends") != null)
2364 Debug.WriteLine("friends");
2367 else if (xElm.Element("delete") != null)
2369 Debug.WriteLine("delete");
2372 if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
2375 long.TryParse(idElm.Value, out id);
2377 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2379 else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
2382 long.TryParse(idElm.Value, out id);
2384 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2388 MyCommon.TraceOut("delete:" + line);
2391 for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
2393 var sEvt = this.StoredEvent[i];
2394 if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
2396 this.StoredEvent.RemoveAt(i);
2401 else if (xElm.Element("limit") != null)
2403 Debug.WriteLine(line);
2406 else if (xElm.Element("event") != null)
2408 Debug.WriteLine("event: " + xElm.Element("event").Value);
2409 CreateEventFromJson(line);
2412 else if (xElm.Element("direct_message") != null)
2414 Debug.WriteLine("direct_message");
2417 else if (xElm.Element("retweeted_status") != null)
2419 var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
2420 var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
2422 // 自分に関係しないリツイートの場合は無視する
2423 var selfUserId = this.UserId.ToString();
2424 if (sourceUserId == selfUserId || targetUserId == selfUserId)
2426 // 公式 RT をイベントとしても扱う
2427 var evt = CreateEventFromRetweet(xElm);
2430 this.StoredEvent.Insert(0, evt);
2432 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2436 // 従来通り公式 RT の表示も行うため return しない
2438 else if (xElm.Element("scrub_geo") != null)
2442 TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
2443 long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
2447 MyCommon.TraceOut("scrub_geo:" + line);
2457 var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
2458 this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
2460 catch (SerializationException ex)
2462 throw TwitterApiException.CreateFromException(ex, line);
2469 var status = TwitterStatus.ParseJson(line);
2470 this.CreatePostsFromJson(new[] { status }, MyCommon.WORKERTYPE.UserStream, null, false);
2472 catch (SerializationException ex)
2474 throw TwitterApiException.CreateFromException(ex, line);
2478 catch (WebApiException ex)
2480 MyCommon.TraceOut(ex);
2483 catch(NullReferenceException)
2485 MyCommon.TraceOut("NullRef StatusArrived: " + line);
2488 this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
2492 /// UserStreamsから受信した公式RTをイベントに変換します
2494 private FormattedEvent CreateEventFromRetweet(XElement xElm)
2496 return new FormattedEvent
2498 Eventtype = MyCommon.EVENTTYPE.Retweet,
2500 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
2501 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
2502 Username = xElm.XPathSelectElement("/user/screen_name").Value,
2503 Target = string.Format("@{0}:{1}", new[]
2505 xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
2506 WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
2508 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
2512 private void CreateEventFromJson(string content)
2514 TwitterStreamEvent eventData = null;
2517 eventData = TwitterStreamEvent.ParseJson(content);
2519 catch(SerializationException ex)
2521 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
2525 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
2528 var evt = new FormattedEvent();
2529 evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
2530 evt.Event = eventData.Event;
2531 evt.Username = eventData.Source.ScreenName;
2532 evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
2534 MyCommon.EVENTTYPE eventType;
2535 eventTable.TryGetValue(eventData.Event, out eventType);
2536 evt.Eventtype = eventType;
2538 TwitterStreamEvent<TwitterStatus> tweetEvent;
2540 switch (eventData.Event)
2542 case "access_revoked":
2543 case "access_unrevoked":
2545 case "user_suspend":
2548 if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
2550 if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
2554 return; //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
2559 evt.Target = "@" + eventData.Target.ScreenName;
2561 case "favorited_retweet":
2562 case "retweeted_retweet":
2566 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2567 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2568 evt.Id = tweetEvent.TargetObject.Id;
2570 if (SettingCommon.Instance.IsRemoveSameEvent)
2572 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2576 var tabinfo = TabInformations.GetInstance();
2579 var statusId = tweetEvent.TargetObject.Id;
2580 if (!tabinfo.Posts.TryGetValue(statusId, out post))
2583 if (eventData.Event == "favorite")
2585 var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2586 if (!favTab.Contains(post.StatusId))
2587 favTab.AddPostImmediately(post.StatusId, post.IsRead);
2589 if (tweetEvent.Source.Id == this.UserId)
2593 else if (tweetEvent.Target.Id == this.UserId)
2595 post.FavoritedCount++;
2597 if (SettingCommon.Instance.FavEventUnread)
2598 tabinfo.SetReadAllTab(post.StatusId, read: false);
2603 if (tweetEvent.Source.Id == this.UserId)
2607 else if (tweetEvent.Target.Id == this.UserId)
2609 post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2613 case "quoted_tweet":
2614 if (evt.IsMe) return;
2616 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2617 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2618 evt.Id = tweetEvent.TargetObject.Id;
2620 if (SettingCommon.Instance.IsRemoveSameEvent)
2622 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2626 case "list_member_added":
2627 case "list_member_removed":
2628 case "list_created":
2629 case "list_destroyed":
2630 case "list_updated":
2631 case "list_user_subscribed":
2632 case "list_user_unsubscribed":
2633 var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2634 evt.Target = listEvent.TargetObject.FullName;
2637 if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2641 if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2650 evt.Target = "@" + eventData.Target.ScreenName;
2651 if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2653 TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2657 evt.Target = "@" + eventData.Target.ScreenName;
2658 if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2660 TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2665 MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2668 this.StoredEvent.Insert(0, evt);
2670 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2673 private void userStream_Started()
2675 this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2678 private void userStream_Stopped()
2680 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2683 public bool UserStreamActive
2684 => this.userStream == null ? false : this.userStream.IsStreamActive;
2686 public void StartUserStream()
2688 var newStream = new TwitterUserstream(this.Api);
2690 newStream.StatusArrived += userStream_StatusArrived;
2691 newStream.Started += userStream_Started;
2692 newStream.Stopped += userStream_Stopped;
2694 newStream.Start(this.AllAtReply, this.TrackWord);
2696 var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2697 oldStream?.Dispose();
2700 public void StopUserStream()
2702 var oldStream = Interlocked.Exchange(ref this.userStream, null);
2703 oldStream?.Dispose();
2706 public void ReconnectUserStream()
2708 this.StartUserStream();
2711 private class TwitterUserstream : IDisposable
2713 public bool AllAtReplies { get; private set; }
2714 public string TrackWords { get; private set; }
2716 public bool IsStreamActive { get; private set; }
2718 public event Action<string> StatusArrived;
2719 public event Action Stopped;
2720 public event Action Started;
2722 private TwitterApi twitterApi;
2724 private Task streamTask;
2725 private CancellationTokenSource streamCts;
2727 public TwitterUserstream(TwitterApi twitterApi)
2729 this.twitterApi = twitterApi;
2732 public void Start(bool allAtReplies, string trackwords)
2734 this.AllAtReplies = allAtReplies;
2735 this.TrackWords = trackwords;
2737 var cts = new CancellationTokenSource();
2739 this.streamCts = cts;
2740 this.streamTask = Task.Run(async () =>
2744 await this.UserStreamLoop(cts.Token)
2745 .ConfigureAwait(false);
2747 catch (OperationCanceledException) { }
2753 this.streamCts?.Cancel();
2755 // streamTask の完了を待たずに IsStreamActive を false にセットする
2756 this.IsStreamActive = false;
2757 this.Stopped?.Invoke();
2760 private async Task UserStreamLoop(CancellationToken cancellationToken)
2762 TimeSpan? sleep = null;
2767 await Task.Delay(sleep.Value, cancellationToken)
2768 .ConfigureAwait(false);
2772 if (!MyCommon.IsNetworkAvailable())
2774 sleep = TimeSpan.FromSeconds(30);
2778 this.IsStreamActive = true;
2779 this.Started?.Invoke();
2783 var replies = this.AllAtReplies ? "all" : null;
2785 using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2786 .ConfigureAwait(false))
2787 using (var reader = new StreamReader(stream))
2789 while (!reader.EndOfStream)
2791 var line = await reader.ReadLineAsync()
2792 .ConfigureAwait(false);
2794 cancellationToken.ThrowIfCancellationRequested();
2796 this.StatusArrived?.Invoke(line);
2800 // キャンセルされていないのにストリームが終了した場合
2801 sleep = TimeSpan.FromSeconds(30);
2803 catch (HttpRequestException) { sleep = TimeSpan.FromSeconds(30); }
2804 catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2805 catch (OperationCanceledException)
2807 if (cancellationToken.IsCancellationRequested)
2810 // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2811 sleep = TimeSpan.FromSeconds(30);
2813 catch (Exception ex)
2815 MyCommon.ExceptionOut(ex);
2816 sleep = TimeSpan.FromSeconds(30);
2820 this.IsStreamActive = false;
2821 this.Stopped?.Invoke();
2826 private bool disposed = false;
2828 public void Dispose()
2833 this.disposed = true;
2837 this.Started = null;
2838 this.Stopped = null;
2839 this.StatusArrived = null;
2844 #region "IDisposable Support"
2845 private bool disposedValue; // 重複する呼び出しを検出するには
2848 protected virtual void Dispose(bool disposing)
2850 if (!this.disposedValue)
2854 this.StopUserStream();
2857 this.disposedValue = true;
2860 //protected Overrides void Finalize()
2862 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2864 // MyBase.Finalize()
2867 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2868 public void Dispose()
2870 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2872 GC.SuppressFinalize(this);
2877 public class PostDeletedEventArgs : EventArgs
2879 public long StatusId { get; }
2881 public PostDeletedEventArgs(long statusId)
2883 this.StatusId = statusId;
2887 public class UserStreamEventReceivedEventArgs : EventArgs
2889 public Twitter.FormattedEvent EventData { get; }
2891 public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2893 this.EventData = eventData;