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 ClearAuthInfo()
200 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
201 this.ResetApiStatus();
202 twCon.ClearAuthInfo();
205 public void VerifyCredentials()
211 res = twCon.VerifyCredentials(ref content);
215 throw new WebApiException("Err:" + ex.Message, ex);
218 this.CheckStatusCode(res, content);
222 var user = TwitterUser.ParseJson(content);
224 this.twCon.AuthenticatedUserId = user.Id;
225 this.UpdateUserStats(user);
227 catch (SerializationException ex)
229 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
230 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
234 public void Initialize(string token, string tokenSecret, string username, long userId)
237 if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
239 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
241 this.ResetApiStatus();
242 this.Api.Initialize(token, tokenSecret, userId, username);
243 twCon.Initialize(token, tokenSecret, username, userId);
244 _uname = username.ToLowerInvariant();
245 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
248 public string PreProcessUrl(string orgData)
252 //var IDNConveter = new IdnMapping();
253 var href = "<a href=\"";
257 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
261 posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
262 posl1 += href.Length;
263 posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
264 urlStr = orgData.Substring(posl1, posl2 - posl1);
266 if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
267 && !urlStr.StartsWith("https://", StringComparison.Ordinal)
268 && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
273 var replacedUrl = MyCommon.IDNEncode(urlStr);
274 if (replacedUrl == null) continue;
275 if (replacedUrl == urlStr) continue;
277 orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
288 private string GetPlainText(string orgData)
290 return WebUtility.HtmlDecode(Regex.Replace(orgData, "(?<tagStart><a [^>]+>)(?<text>[^<]+)(?<tagEnd></a>)", "${text}"));
293 // htmlの簡易サニタイズ(詳細表示に不要なタグの除去)
295 private string SanitizeHtml(string orgdata)
297 var retdata = orgdata;
299 retdata = Regex.Replace(retdata, "<(script|object|applet|image|frameset|fieldset|legend|style).*" +
300 "</(script|object|applet|image|frameset|fieldset|legend|style)>", "", RegexOptions.IgnoreCase);
302 retdata = Regex.Replace(retdata, "<(frame|link|iframe|img)>", "", RegexOptions.IgnoreCase);
307 private string AdjustHtml(string orgData)
309 var retStr = orgData;
310 //var m = Regex.Match(retStr, "<a [^>]+>[#|#](?<1>[a-zA-Z0-9_]+)</a>");
315 // _hashList.Add("#" + m.Groups(1).Value);
319 retStr = Regex.Replace(retStr, "<a [^>]*href=\"/", "<a href=\"https://twitter.com/");
320 retStr = retStr.Replace("<a href=", "<a target=\"_self\" href=");
321 retStr = Regex.Replace(retStr, @"(\r\n?|\n)", "<br>"); // CRLF, CR, LF は全て <br> に置換する
323 //半角スペースを置換(Thanks @anis774)
327 ret = EscapeSpace(ref retStr);
330 return SanitizeHtml(retStr);
333 private bool EscapeSpace(ref string html)
335 //半角スペースを置換(Thanks @anis774)
337 for (int i = 0; i < html.Length; i++)
348 if ((!isTag) && (html[i] == ' '))
350 html = html.Remove(i, 1);
351 html = html.Insert(i, " ");
358 private struct PostInfo
360 public string CreatedAt;
363 public string UserId;
364 public PostInfo(string Created, string IdStr, string txt, string uid)
371 public bool Equals(PostInfo dst)
373 if (this.CreatedAt == dst.CreatedAt && this.Id == dst.Id && this.Text == dst.Text && this.UserId == dst.UserId)
384 static private PostInfo _prev = new PostInfo("", "", "", "");
385 private bool IsPostRestricted(TwitterStatus status)
387 var _current = new PostInfo("", "", "", "");
389 _current.CreatedAt = status.CreatedAt;
390 _current.Id = status.IdStr;
391 if (status.Text == null)
397 _current.Text = status.Text;
399 _current.UserId = status.User.IdStr;
401 if (_current.Equals(_prev))
405 _prev.CreatedAt = _current.CreatedAt;
406 _prev.Id = _current.Id;
407 _prev.Text = _current.Text;
408 _prev.UserId = _current.UserId;
413 public async Task PostStatus(string postStr, long? reply_to, IReadOnlyList<long> mediaIds = null)
415 this.CheckAccountState();
417 if (mediaIds == null &&
418 Twitter.DMSendTextRegex.IsMatch(postStr))
420 await this.SendDirectMessage(postStr)
421 .ConfigureAwait(false);
425 var response = await this.Api.StatusesUpdate(postStr, reply_to, mediaIds)
426 .ConfigureAwait(false);
428 var status = await response.LoadJsonAsync()
429 .ConfigureAwait(false);
431 this.UpdateUserStats(status.User);
433 if (IsPostRestricted(status))
435 throw new WebApiException("OK:Delaying?");
439 public async Task PostStatusWithMultipleMedia(string postStr, long? reply_to, IMediaItem[] mediaItems)
441 this.CheckAccountState();
443 if (Twitter.DMSendTextRegex.IsMatch(postStr))
445 await this.SendDirectMessage(postStr)
446 .ConfigureAwait(false);
450 if (mediaItems.Length == 0)
451 throw new WebApiException("Err:Invalid Files!");
453 var uploadTasks = from m in mediaItems
454 select this.UploadMedia(m);
456 var mediaIds = await Task.WhenAll(uploadTasks)
457 .ConfigureAwait(false);
459 await this.PostStatus(postStr, reply_to, mediaIds)
460 .ConfigureAwait(false);
463 public async Task<long> UploadMedia(IMediaItem item)
465 this.CheckAccountState();
467 var response = await this.Api.MediaUpload(item)
468 .ConfigureAwait(false);
470 var media = await response.LoadJsonAsync()
471 .ConfigureAwait(false);
473 return media.MediaId;
476 public async Task SendDirectMessage(string postStr)
478 this.CheckAccountState();
479 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
481 var mc = Twitter.DMSendTextRegex.Match(postStr);
483 var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
484 .ConfigureAwait(false);
486 var dm = await response.LoadJsonAsync()
487 .ConfigureAwait(false);
489 this.UpdateUserStats(dm.Sender);
492 public async Task PostRetweet(long id, bool read)
494 this.CheckAccountState();
498 var post = TabInformations.GetInstance()[id];
501 throw new WebApiException("Err:Target isn't found.");
503 if (TabInformations.GetInstance()[id].RetweetedId != null)
505 target = TabInformations.GetInstance()[id].RetweetedId.Value; //再RTの場合は元発言をRT
508 var response = await this.Api.StatusesRetweet(target)
509 .ConfigureAwait(false);
511 var status = await response.LoadJsonAsync()
512 .ConfigureAwait(false);
515 post = CreatePostsFromStatusData(status);
517 throw new WebApiException("Invalid Json!");
522 if (TabInformations.GetInstance().ContainsKey(post.StatusId))
526 if (post.RetweetedId == null)
527 throw new WebApiException("Invalid Json!");
533 if (_readOwnPost) post.IsRead = true;
536 TabInformations.GetInstance().AddPost(post);
539 public string Username
543 return twCon.AuthenticatedUsername;
551 return twCon.AuthenticatedUserId;
555 public string Password
559 return twCon.Password;
563 private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
564 public static MyCommon.ACCOUNT_STATE AccountState
568 return _accountState;
572 _accountState = value;
576 public bool RestrictFavCheck { get; set; }
579 public void GetTweenBinary(string strVer)
584 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/Tween" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
585 Path.Combine(MyCommon.settingPath, "TweenNew.exe")))
587 throw new WebApiException("Err:Download failed");
590 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, "en")))
592 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, "en"));
594 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenResEn" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
595 Path.Combine(Path.Combine(MyCommon.settingPath, "en"), "Tween.resourcesNew.dll")))
597 throw new WebApiException("Err:Download failed");
599 //その他言語圏のリソース。取得失敗しても継続
602 if (!Thread.CurrentThread.CurrentUICulture.IsNeutralCulture)
604 var idx = Thread.CurrentThread.CurrentUICulture.Name.LastIndexOf('-');
607 curCul = Thread.CurrentThread.CurrentUICulture.Name.Substring(0, idx);
611 curCul = Thread.CurrentThread.CurrentUICulture.Name;
616 curCul = Thread.CurrentThread.CurrentUICulture.Name;
618 if (!string.IsNullOrEmpty(curCul) && curCul != "en" && curCul != "ja")
620 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul)))
622 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul));
624 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
625 Path.Combine(Path.Combine(MyCommon.settingPath, curCul), "Tween.resourcesNew.dll")))
627 //return "Err:Download failed";
632 if (!Thread.CurrentThread.CurrentCulture.IsNeutralCulture)
634 var idx = Thread.CurrentThread.CurrentCulture.Name.LastIndexOf('-');
637 curCul2 = Thread.CurrentThread.CurrentCulture.Name.Substring(0, idx);
641 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
646 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
648 if (!string.IsNullOrEmpty(curCul2) && curCul2 != "en" && curCul2 != curCul)
650 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul2)))
652 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul2));
654 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul2 + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
655 Path.Combine(Path.Combine(MyCommon.settingPath, curCul2), "Tween.resourcesNew.dll")))
657 //return "Err:Download failed";
662 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenUp3.gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
663 Path.Combine(MyCommon.settingPath, "TweenUp3.exe")))
665 throw new WebApiException("Err:Download failed");
668 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenDll" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
669 Path.Combine(MyCommon.settingPath, "TweenNew.XmlSerializers.dll")))
671 throw new WebApiException("Err:Download failed");
676 throw new WebApiException("Err:Download failed", ex);
681 public bool ReadOwnPost
689 _readOwnPost = value;
693 public int FollowersCount { get; private set; }
694 public int FriendsCount { get; private set; }
695 public int StatusesCount { get; private set; }
696 public string Location { get; private set; } = "";
697 public string Bio { get; private set; } = "";
699 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
700 private void UpdateUserStats(TwitterUser self)
702 this.FollowersCount = self.FollowersCount;
703 this.FriendsCount = self.FriendsCount;
704 this.StatusesCount = self.StatusesCount;
705 this.Location = self.Location;
706 this.Bio = self.Description;
710 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
712 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
714 return count >= 20 && count <= GetMaxApiResultCount(type);
718 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
720 public static bool VerifyMoreApiResultCount(int count)
722 return count >= 20 && count <= 200;
726 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
728 public static bool VerifyFirstApiResultCount(int count)
730 return count >= 20 && count <= 200;
734 /// WORKERTYPEに応じた取得可能な最大件数を取得する
736 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
738 // 参照: REST APIs - 各endpointのcountパラメータ
739 // https://dev.twitter.com/rest/public
742 case MyCommon.WORKERTYPE.Timeline:
743 case MyCommon.WORKERTYPE.Reply:
744 case MyCommon.WORKERTYPE.UserTimeline:
745 case MyCommon.WORKERTYPE.Favorites:
746 case MyCommon.WORKERTYPE.DirectMessegeRcv:
747 case MyCommon.WORKERTYPE.DirectMessegeSnt:
748 case MyCommon.WORKERTYPE.List: // 不明
751 case MyCommon.WORKERTYPE.PublicSearch:
755 throw new InvalidOperationException("Invalid type: " + type);
760 /// WORKERTYPEに応じた取得件数を取得する
762 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
764 if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
765 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
770 if (SettingCommon.Instance.UseAdditionalCount)
774 case MyCommon.WORKERTYPE.Favorites:
775 if (SettingCommon.Instance.FavoritesCountApi != 0)
776 return SettingCommon.Instance.FavoritesCountApi;
778 case MyCommon.WORKERTYPE.List:
779 if (SettingCommon.Instance.ListCountApi != 0)
780 return SettingCommon.Instance.ListCountApi;
782 case MyCommon.WORKERTYPE.PublicSearch:
783 if (SettingCommon.Instance.SearchCountApi != 0)
784 return SettingCommon.Instance.SearchCountApi;
786 case MyCommon.WORKERTYPE.UserTimeline:
787 if (SettingCommon.Instance.UserTimelineCountApi != 0)
788 return SettingCommon.Instance.UserTimelineCountApi;
791 if (more && SettingCommon.Instance.MoreCountApi != 0)
793 return Math.Min(SettingCommon.Instance.MoreCountApi, GetMaxApiResultCount(type));
795 if (startup && SettingCommon.Instance.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
797 return Math.Min(SettingCommon.Instance.FirstCountApi, GetMaxApiResultCount(type));
802 var count = SettingCommon.Instance.CountApi;
804 if (type == MyCommon.WORKERTYPE.Reply)
805 count = SettingCommon.Instance.CountApiReply;
807 return Math.Min(count, GetMaxApiResultCount(type));
810 public async Task GetTimelineApi(bool read, MyCommon.WORKERTYPE gType, bool more, bool startup)
812 this.CheckAccountState();
814 var count = GetApiResultCount(gType, more, startup);
816 TwitterStatus[] statuses;
817 if (gType == MyCommon.WORKERTYPE.Timeline)
821 statuses = await this.Api.StatusesHomeTimeline(count, maxId: this.minHomeTimeline)
822 .ConfigureAwait(false);
826 statuses = await this.Api.StatusesHomeTimeline(count)
827 .ConfigureAwait(false);
834 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: this.minMentions)
835 .ConfigureAwait(false);
839 statuses = await this.Api.StatusesMentionsTimeline(count)
840 .ConfigureAwait(false);
844 var minimumId = CreatePostsFromJson(statuses, gType, null, read);
846 if (minimumId != null)
848 if (gType == MyCommon.WORKERTYPE.Timeline)
849 this.minHomeTimeline = minimumId.Value;
851 this.minMentions = minimumId.Value;
855 public async Task GetUserTimelineApi(bool read, string userName, TabClass tab, bool more)
857 this.CheckAccountState();
859 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
861 TwitterStatus[] statuses;
862 if (string.IsNullOrEmpty(userName))
864 var target = tab.User;
865 if (string.IsNullOrEmpty(target)) return;
867 statuses = await this.Api.StatusesUserTimeline(userName, count)
868 .ConfigureAwait(false);
874 statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
875 .ConfigureAwait(false);
879 statuses = await this.Api.StatusesUserTimeline(userName, count)
880 .ConfigureAwait(false);
884 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
886 if (minimumId != null)
887 tab.OldestId = minimumId.Value;
890 public async Task<PostClass> GetStatusApi(bool read, long id)
892 this.CheckAccountState();
894 var status = await this.Api.StatusesShow(id)
895 .ConfigureAwait(false);
897 var item = CreatePostsFromStatusData(status);
899 throw new WebApiException("Err:Can't create post");
902 if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
907 public async Task GetStatusApi(bool read, long id, TabClass tab)
909 var post = await this.GetStatusApi(read, id)
910 .ConfigureAwait(false);
912 //非同期アイコン取得&StatusDictionaryに追加
913 if (tab != null && tab.IsInnerStorageTabType)
914 tab.AddPostToInnerStorage(post);
916 TabInformations.GetInstance().AddPost(post);
919 private PostClass CreatePostsFromStatusData(TwitterStatus status)
921 return CreatePostsFromStatusData(status, false);
924 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
926 var post = new PostClass();
927 TwitterEntities entities;
930 post.StatusId = status.Id;
931 if (status.RetweetedStatus != null)
933 var retweeted = status.RetweetedStatus;
935 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
938 post.RetweetedId = retweeted.Id;
940 post.TextFromApi = retweeted.Text;
941 entities = retweeted.MergedEntities;
942 sourceHtml = retweeted.Source;
944 post.InReplyToStatusId = retweeted.InReplyToStatusId;
945 post.InReplyToUser = retweeted.InReplyToScreenName;
946 post.InReplyToUserId = status.InReplyToUserId;
955 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
956 post.IsFav = tc.Contains(retweeted.Id);
959 if (retweeted.Coordinates != null)
960 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
963 var user = retweeted.User;
965 if (user == null || user.ScreenName == null || status.User.ScreenName == null) return null;
967 post.UserId = user.Id;
968 post.ScreenName = user.ScreenName;
969 post.Nickname = user.Name.Trim();
970 post.ImageUrl = user.ProfileImageUrlHttps;
971 post.IsProtect = user.Protected;
974 post.RetweetedBy = status.User.ScreenName;
975 post.RetweetedByUserId = status.User.Id;
976 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
980 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
982 post.TextFromApi = status.Text;
983 entities = status.MergedEntities;
984 sourceHtml = status.Source;
985 post.InReplyToStatusId = status.InReplyToStatusId;
986 post.InReplyToUser = status.InReplyToScreenName;
987 post.InReplyToUserId = status.InReplyToUserId;
996 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
997 post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
1000 if (status.Coordinates != null)
1001 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
1004 var user = status.User;
1006 if (user == null || user.ScreenName == null) return null;
1008 post.UserId = user.Id;
1009 post.ScreenName = user.ScreenName;
1010 post.Nickname = user.Name.Trim();
1011 post.ImageUrl = user.ProfileImageUrlHttps;
1012 post.IsProtect = user.Protected;
1013 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
1016 string textFromApi = post.TextFromApi;
1017 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
1018 post.TextFromApi = textFromApi;
1019 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
1020 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1021 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1023 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
1024 .Where(x => x != post.StatusId && x != post.RetweetedId)
1025 .Distinct().ToArray();
1027 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
1028 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1032 var source = ParseSource(sourceHtml);
1033 post.Source = source.Item1;
1034 post.SourceUri = source.Item2;
1036 post.IsReply = post.ReplyToList.Contains(_uname);
1037 post.IsExcludeReply = false;
1045 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
1053 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
1055 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
1057 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
1059 return GetQuoteTweetStatusIds(urls);
1062 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
1064 foreach (var url in urls)
1066 var match = Twitter.StatusUrlRegex.Match(url);
1070 if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
1071 yield return statusId;
1076 private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabClass tab, bool read)
1078 long? minimumId = null;
1080 foreach (var status in items)
1082 PostClass post = null;
1083 post = CreatePostsFromStatusData(status);
1084 if (post == null) continue;
1086 if (minimumId == null || minimumId.Value > post.StatusId)
1087 minimumId = post.StatusId;
1094 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1098 if (tab.Contains(post.StatusId)) continue;
1103 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
1104 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
1107 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1109 //非同期アイコン取得&StatusDictionaryに追加
1110 if (tab != null && tab.IsInnerStorageTabType)
1111 tab.AddPostToInnerStorage(post);
1113 TabInformations.GetInstance().AddPost(post);
1119 private long? CreatePostsFromSearchJson(string content, TabClass tab, bool read, int count, bool more)
1121 TwitterSearchResult items;
1124 items = TwitterSearchResult.ParseJson(content);
1126 catch (SerializationException ex)
1128 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1129 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1131 catch (Exception ex)
1133 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1134 throw new WebApiException("Invalid Json!", content, ex);
1137 long? minimumId = null;
1139 foreach (var result in items.Statuses)
1141 var post = CreatePostsFromStatusData(result);
1145 if (minimumId == null || minimumId.Value > post.StatusId)
1146 minimumId = post.StatusId;
1148 if (!more && post.StatusId > tab.SinceId) tab.SinceId = post.StatusId;
1154 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1158 if (tab.Contains(post.StatusId)) continue;
1163 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
1165 //非同期アイコン取得&StatusDictionaryに追加
1166 if (tab != null && tab.IsInnerStorageTabType)
1167 tab.AddPostToInnerStorage(post);
1169 TabInformations.GetInstance().AddPost(post);
1175 private void CreateFavoritePostsFromJson(string content, bool read)
1177 TwitterStatus[] item;
1180 item = TwitterStatus.ParseJsonArray(content);
1182 catch (SerializationException ex)
1184 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1185 throw new WebApiException("Json Parse Error(DataContractJsonSerializer)", content, ex);
1187 catch (Exception ex)
1189 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1190 throw new WebApiException("Invalid Json!", content, ex);
1193 var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1195 foreach (var status in item)
1200 if (favTab.Contains(status.Id)) continue;
1203 var post = CreatePostsFromStatusData(status, true);
1204 if (post == null) continue;
1208 TabInformations.GetInstance().AddPost(post);
1212 public async Task GetListStatus(bool read, TabClass tab, bool more, bool startup)
1214 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
1216 TwitterStatus[] statuses;
1219 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
1220 .ConfigureAwait(false);
1224 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
1225 .ConfigureAwait(false);
1228 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
1230 if (minimumId != null)
1231 tab.OldestId = minimumId.Value;
1235 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1237 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1238 internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1240 if (!posts.ContainsKey(startStatusId))
1241 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1243 var nextPost = posts[startStatusId];
1244 while (nextPost.InReplyToStatusId != null)
1246 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1248 nextPost = posts[nextPost.InReplyToStatusId.Value];
1254 public async Task GetRelatedResult(bool read, TabClass tab)
1256 var relPosts = new Dictionary<Int64, PostClass>();
1257 if (tab.RelationTargetPost.TextFromApi.Contains("@") && tab.RelationTargetPost.InReplyToStatusId == null)
1260 var p = TabInformations.GetInstance()[tab.RelationTargetPost.StatusId];
1261 if (p != null && p.InReplyToStatusId != null)
1263 tab.RelationTargetPost = p;
1267 p = await this.GetStatusApi(read, tab.RelationTargetPost.StatusId)
1268 .ConfigureAwait(false);
1269 tab.RelationTargetPost = p;
1272 relPosts.Add(tab.RelationTargetPost.StatusId, tab.RelationTargetPost);
1274 Exception lastException = null;
1276 // in_reply_to_status_id を使用してリプライチェインを辿る
1277 var nextPost = FindTopOfReplyChain(relPosts, tab.RelationTargetPost.StatusId);
1279 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1281 var inReplyToId = nextPost.InReplyToStatusId.Value;
1283 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1284 if (inReplyToPost == null)
1288 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1289 .ConfigureAwait(false);
1291 catch (WebApiException ex)
1298 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1300 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1303 //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1304 var text = tab.RelationTargetPost.Text;
1305 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1306 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1307 foreach (var _match in ma)
1310 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1312 if (relPosts.ContainsKey(_statusId))
1315 var p = TabInformations.GetInstance()[_statusId];
1320 p = await this.GetStatusApi(read, _statusId)
1321 .ConfigureAwait(false);
1323 catch (WebApiException ex)
1331 relPosts.Add(p.StatusId, p);
1335 relPosts.Values.ToList().ForEach(p =>
1337 if (p.IsMe && !read && this._readOwnPost)
1342 tab.AddPostToInnerStorage(p);
1345 if (lastException != null)
1346 throw new WebApiException(lastException.Message, lastException);
1349 public void GetSearch(bool read,
1355 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1357 long? sinceId = null;
1360 maxId = tab.OldestId - 1;
1364 sinceId = tab.SinceId;
1369 // TODO:一時的に40>100件に 件数変更UI作成の必要あり
1370 res = twCon.Search(tab.SearchWords, tab.SearchLang, count, maxId, sinceId, ref content);
1374 throw new WebApiException("Err:" + ex.Message, ex);
1378 case HttpStatusCode.BadRequest:
1379 throw new WebApiException("Invalid query", content);
1380 case HttpStatusCode.NotFound:
1381 throw new WebApiException("Invalid query", content);
1382 case HttpStatusCode.PaymentRequired: //API Documentには420と書いてあるが、該当コードがないので402にしてある
1383 throw new WebApiException("Search API Limit?", content);
1384 case HttpStatusCode.OK:
1387 throw new WebApiException("Err:" + res.ToString() + "(" + MethodBase.GetCurrentMethod().Name + ")", content);
1390 if (!TabInformations.GetInstance().ContainsTab(tab))
1393 var minimumId = this.CreatePostsFromSearchJson(content, tab, read, count, more);
1395 if (minimumId != null)
1396 tab.OldestId = minimumId.Value;
1399 private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read)
1401 foreach (var message in item)
1403 var post = new PostClass();
1406 post.StatusId = message.Id;
1407 if (gType != MyCommon.WORKERTYPE.UserStream)
1409 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1411 if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1415 if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1422 if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1426 post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1428 var textFromApi = message.Text;
1430 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
1431 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
1432 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1433 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1436 post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
1438 post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1439 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1444 if (gType == MyCommon.WORKERTYPE.UserStream)
1446 if (twCon.AuthenticatedUsername.Equals(message.Recipient.ScreenName, StringComparison.CurrentCultureIgnoreCase))
1448 user = message.Sender;
1454 user = message.Recipient;
1461 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1463 user = message.Sender;
1469 user = message.Recipient;
1475 post.UserId = user.Id;
1476 post.ScreenName = user.ScreenName;
1477 post.Nickname = user.Name.Trim();
1478 post.ImageUrl = user.ProfileImageUrlHttps;
1479 post.IsProtect = user.Protected;
1483 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name);
1484 MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1489 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1490 post.IsReply = false;
1491 post.IsExcludeReply = false;
1494 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1495 dmTab.AddPostToInnerStorage(post);
1499 public async Task GetDirectMessageApi(bool read, MyCommon.WORKERTYPE gType, bool more)
1501 this.CheckAccountState();
1502 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1504 var count = GetApiResultCount(gType, more, false);
1506 TwitterDirectMessage[] messages;
1507 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1511 messages = await this.Api.DirectMessagesRecv(count, maxId: this.minDirectmessage)
1512 .ConfigureAwait(false);
1516 messages = await this.Api.DirectMessagesRecv(count)
1517 .ConfigureAwait(false);
1524 messages = await this.Api.DirectMessagesSent(count, maxId: this.minDirectmessageSent)
1525 .ConfigureAwait(false);
1529 messages = await this.Api.DirectMessagesSent(count)
1530 .ConfigureAwait(false);
1534 CreateDirectMessagesFromJson(messages, gType, read);
1537 public void GetFavoritesApi(bool read,
1540 this.CheckAccountState();
1544 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
1548 res = twCon.Favorites(count, ref content);
1552 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1555 this.CheckStatusCode(res, content);
1557 CreateFavoritePostsFromJson(content, read);
1560 private string ReplaceTextFromApi(string text, TwitterEntities entities)
1562 if (entities != null)
1564 if (entities.Urls != null)
1566 foreach (var m in entities.Urls)
1568 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1571 if (entities.Media != null)
1573 foreach (var m in entities.Media)
1575 if (m.AltText != null)
1577 text = text.Replace(m.Url, string.Format(Properties.Resources.ImageAltText, m.AltText));
1581 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1592 /// <exception cref="WebApiException"/>
1593 public async Task RefreshFollowerIds()
1595 if (MyCommon._endingFlag) return;
1598 var newFollowerIds = new HashSet<long>();
1601 var ret = await this.Api.FollowersIds(cursor)
1602 .ConfigureAwait(false);
1604 if (ret.Ids == null)
1605 throw new WebApiException("ret.ids == null");
1607 newFollowerIds.UnionWith(ret.Ids);
1608 cursor = ret.NextCursor;
1609 } while (cursor != 0);
1611 this.followerId = newFollowerIds;
1612 TabInformations.GetInstance().RefreshOwl(this.followerId);
1614 this._GetFollowerResult = true;
1617 public bool GetFollowersSuccess
1621 return _GetFollowerResult;
1626 /// RT 非表示ユーザーを更新します
1628 /// <exception cref="WebApiException"/>
1629 public async Task RefreshNoRetweetIds()
1631 if (MyCommon._endingFlag) return;
1633 this.noRTId = await this.Api.NoRetweetIds()
1634 .ConfigureAwait(false);
1636 this._GetNoRetweetResult = true;
1639 public bool GetNoRetweetSuccess
1643 return _GetNoRetweetResult;
1648 /// t.co の文字列長などの設定情報を更新します
1650 /// <exception cref="WebApiException"/>
1651 public async Task RefreshConfiguration()
1653 this.Configuration = await this.Api.Configuration()
1654 .ConfigureAwait(false);
1657 public async Task GetListsApi()
1659 this.CheckAccountState();
1661 var ownedLists = await TwitterLists.GetAllItemsAsync(x => this.Api.ListsOwnerships(this.Username, cursor: x))
1662 .ConfigureAwait(false);
1664 var subscribedLists = await TwitterLists.GetAllItemsAsync(x => this.Api.ListsSubscriptions(this.Username, cursor: x))
1665 .ConfigureAwait(false);
1667 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1668 .Select(x => new ListElement(x, this))
1672 public async Task DeleteList(long listId)
1674 await this.Api.ListsDestroy(listId)
1676 .ConfigureAwait(false);
1678 var tabinfo = TabInformations.GetInstance();
1680 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1681 .Where(x => x.Id != listId)
1685 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1687 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1688 .ConfigureAwait(false);
1690 var list = await response.LoadJsonAsync()
1691 .ConfigureAwait(false);
1693 return new ListElement(list, this);
1696 public long GetListMembers(string list_id, List<UserInfo> lists, long cursor)
1698 this.CheckAccountState();
1704 res = twCon.GetListMembers(this.Username, list_id, cursor, ref content);
1708 throw new WebApiException("Err:" + ex.Message);
1711 this.CheckStatusCode(res, content);
1715 var users = TwitterUsers.ParseJson(content);
1716 Array.ForEach<TwitterUser>(
1718 u => lists.Add(new UserInfo(u)));
1720 return users.NextCursor;
1722 catch(SerializationException ex)
1724 MyCommon.TraceOut(ex.Message + Environment.NewLine + content);
1725 throw new WebApiException("Err:Json Parse Error(DataContractJsonSerializer)", content, ex);
1729 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name + " " + content);
1730 throw new WebApiException("Err:Invalid Json!", content, ex);
1734 public async Task CreateListApi(string listName, bool isPrivate, string description)
1736 this.CheckAccountState();
1738 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1739 .ConfigureAwait(false);
1741 var list = await response.LoadJsonAsync()
1742 .ConfigureAwait(false);
1744 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1747 public bool ContainsUserAtList(string listId, string user)
1749 this.CheckAccountState();
1756 res = this.twCon.ShowListMember(listId, user, ref content);
1760 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1763 if (res == HttpStatusCode.NotFound)
1768 this.CheckStatusCode(res, content);
1772 TwitterUser.ParseJson(content);
1781 public void AddUserToList(string listId, string user)
1788 res = twCon.CreateListMembers(listId, user, ref content);
1792 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1795 this.CheckStatusCode(res, content);
1798 public void RemoveUserToList(string listId, string user)
1805 res = twCon.DeleteListMembers(listId, user, ref content);
1809 throw new WebApiException("Err:" + ex.Message + "(" + MethodBase.GetCurrentMethod().Name + ")", ex);
1812 this.CheckStatusCode(res, content);
1815 public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
1817 if (entities != null)
1819 if (entities.Hashtags != null)
1823 this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1826 if (entities.UserMentions != null)
1828 foreach (var ent in entities.UserMentions)
1830 var screenName = ent.ScreenName.ToLowerInvariant();
1831 if (!AtList.Contains(screenName))
1832 AtList.Add(screenName);
1835 if (entities.Media != null)
1839 foreach (var ent in entities.Media)
1841 if (!media.Any(x => x.Url == ent.MediaUrl))
1843 if (ent.VideoInfo != null &&
1844 ent.Type == "animated_gif" || ent.Type == "video")
1846 //var videoUrl = ent.VideoInfo.Variants
1847 // .Where(v => v.ContentType == "video/mp4")
1848 // .OrderByDescending(v => v.Bitrate)
1849 // .Select(v => v.Url).FirstOrDefault();
1850 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, ent.ExpandedUrl));
1853 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, videoUrl: null));
1860 // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
1861 text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
1863 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>");
1864 text = PreProcessUrl(text); //IDN置換
1869 private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
1872 /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
1874 public static Tuple<string, Uri> ParseSource(string sourceHtml)
1876 if (string.IsNullOrEmpty(sourceHtml))
1877 return Tuple.Create<string, Uri>("", null);
1882 // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
1884 var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
1887 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
1890 var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
1891 sourceUri = new Uri(SourceUriBase, uriStr);
1893 catch (UriFormatException)
1900 sourceText = WebUtility.HtmlDecode(sourceHtml);
1904 return Tuple.Create(sourceText, sourceUri);
1907 public async Task<TwitterApiStatus> GetInfoApi()
1909 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1911 if (MyCommon._endingFlag) return null;
1913 var limits = await this.Api.ApplicationRateLimitStatus()
1914 .ConfigureAwait(false);
1916 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1918 return MyCommon.TwitterApiInfo;
1922 /// ブロック中のユーザーを更新します
1924 /// <exception cref="WebApiException"/>
1925 public async Task RefreshBlockIds()
1927 if (MyCommon._endingFlag) return;
1930 var newBlockIds = new HashSet<long>();
1933 var ret = await this.Api.BlocksIds(cursor)
1934 .ConfigureAwait(false);
1936 newBlockIds.UnionWith(ret.Ids);
1937 cursor = ret.NextCursor;
1938 } while (cursor != 0);
1940 newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
1942 TabInformations.GetInstance().BlockIds = newBlockIds;
1946 /// ミュート中のユーザーIDを更新します
1948 /// <exception cref="WebApiException"/>
1949 public async Task RefreshMuteUserIdsAsync()
1951 if (MyCommon._endingFlag) return;
1953 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1954 .ConfigureAwait(false);
1956 TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
1959 public string[] GetHashList()
1964 hashArray = _hashList.ToArray();
1970 public string AccessToken
1974 return twCon.AccessToken;
1978 public string AccessTokenSecret
1982 return twCon.AccessTokenSecret;
1986 private void CheckAccountState()
1988 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1989 throw new WebApiException("Auth error. Check your account");
1992 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1994 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1995 throw new WebApiException("Auth Err:try to re-authorization.");
1998 private void CheckStatusCode(HttpStatusCode httpStatus, string responseText,
1999 [CallerMemberName] string callerMethodName = "")
2001 if (httpStatus == HttpStatusCode.OK)
2003 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
2007 if (string.IsNullOrWhiteSpace(responseText))
2009 if (httpStatus == HttpStatusCode.Unauthorized)
2010 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2012 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")");
2017 var errors = TwitterError.ParseJson(responseText).Errors;
2018 if (errors == null || !errors.Any())
2020 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2023 foreach (var error in errors)
2025 if (error.Code == TwitterErrorCode.InvalidToken ||
2026 error.Code == TwitterErrorCode.SuspendedAccount)
2028 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
2032 throw new WebApiException("Err:" + string.Join(",", errors.Select(x => x.ToString())) + "(" + callerMethodName + ")", responseText);
2034 catch (SerializationException) { }
2036 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
2039 public int GetTextLengthRemain(string postText)
2041 var matchDm = Twitter.DMSendTextRegex.Match(postText);
2042 if (matchDm.Success)
2043 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
2045 return this.GetTextLengthRemainInternal(postText, isDm: false);
2048 private int GetTextLengthRemainInternal(string postText, bool isDm)
2053 while (pos < postText.Length)
2057 if (char.IsSurrogatePair(postText, pos))
2058 pos += 2; // サロゲートペアの場合は2文字分進める
2063 var urls = TweetExtractor.ExtractUrls(postText);
2064 foreach (var url in urls)
2066 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
2067 ? this.Configuration.ShortUrlLengthHttps
2068 : this.Configuration.ShortUrlLength;
2070 textLength += shortUrlLength - url.Length;
2074 return this.Configuration.DmTextCharacterLimit - textLength;
2076 return 140 - textLength;
2080 #region "UserStream"
2081 private string trackWord_ = "";
2082 public string TrackWord
2093 private bool allAtReply_ = false;
2094 public bool AllAtReply
2102 allAtReply_ = value;
2106 public event EventHandler NewPostFromStream;
2107 public event EventHandler UserStreamStarted;
2108 public event EventHandler UserStreamStopped;
2109 public event EventHandler<PostDeletedEventArgs> PostDeleted;
2110 public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
2111 private DateTime _lastUserstreamDataReceived;
2112 private TwitterUserstream userStream;
2114 public class FormattedEvent
2116 public MyCommon.EVENTTYPE Eventtype { get; set; }
2117 public DateTime CreatedAt { get; set; }
2118 public string Event { get; set; }
2119 public string Username { get; set; }
2120 public string Target { get; set; }
2121 public Int64 Id { get; set; }
2122 public bool IsMe { get; set; }
2125 public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
2126 public List<FormattedEvent> StoredEvent
2130 return storedEvent_;
2134 storedEvent_ = value;
2138 private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
2140 ["favorite"] = MyCommon.EVENTTYPE.Favorite,
2141 ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
2142 ["follow"] = MyCommon.EVENTTYPE.Follow,
2143 ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
2144 ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
2145 ["block"] = MyCommon.EVENTTYPE.Block,
2146 ["unblock"] = MyCommon.EVENTTYPE.Unblock,
2147 ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
2148 ["deleted"] = MyCommon.EVENTTYPE.Deleted,
2149 ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
2150 ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
2151 ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
2152 ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
2153 ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
2154 ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
2155 ["mute"] = MyCommon.EVENTTYPE.Mute,
2156 ["unmute"] = MyCommon.EVENTTYPE.Unmute,
2157 ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
2160 public bool IsUserstreamDataReceived
2164 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
2168 private void userStream_StatusArrived(string line)
2170 this._lastUserstreamDataReceived = DateTime.Now;
2171 if (string.IsNullOrEmpty(line)) return;
2173 if (line.First() != '{' || line.Last() != '}')
2175 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
2183 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
2185 var xElm = XElement.Load(jsonReader);
2186 if (xElm.Element("friends") != null)
2188 Debug.WriteLine("friends");
2191 else if (xElm.Element("delete") != null)
2193 Debug.WriteLine("delete");
2196 if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
2199 long.TryParse(idElm.Value, out id);
2201 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2203 else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
2206 long.TryParse(idElm.Value, out id);
2208 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2212 MyCommon.TraceOut("delete:" + line);
2215 for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
2217 var sEvt = this.StoredEvent[i];
2218 if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
2220 this.StoredEvent.RemoveAt(i);
2225 else if (xElm.Element("limit") != null)
2227 Debug.WriteLine(line);
2230 else if (xElm.Element("event") != null)
2232 Debug.WriteLine("event: " + xElm.Element("event").Value);
2233 CreateEventFromJson(line);
2236 else if (xElm.Element("direct_message") != null)
2238 Debug.WriteLine("direct_message");
2241 else if (xElm.Element("retweeted_status") != null)
2243 var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
2244 var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
2246 // 自分に関係しないリツイートの場合は無視する
2247 var selfUserId = this.UserId.ToString();
2248 if (sourceUserId == selfUserId || targetUserId == selfUserId)
2250 // 公式 RT をイベントとしても扱う
2251 var evt = CreateEventFromRetweet(xElm);
2254 this.StoredEvent.Insert(0, evt);
2256 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2260 // 従来通り公式 RT の表示も行うため return しない
2262 else if (xElm.Element("scrub_geo") != null)
2266 TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
2267 long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
2271 MyCommon.TraceOut("scrub_geo:" + line);
2281 var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
2282 this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
2284 catch (SerializationException ex)
2286 throw TwitterApiException.CreateFromException(ex, line);
2293 var status = TwitterStatus.ParseJson(line);
2294 this.CreatePostsFromJson(new[] { status }, MyCommon.WORKERTYPE.UserStream, null, false);
2296 catch (SerializationException ex)
2298 throw TwitterApiException.CreateFromException(ex, line);
2302 catch (WebApiException ex)
2304 MyCommon.TraceOut(ex);
2307 catch(NullReferenceException)
2309 MyCommon.TraceOut("NullRef StatusArrived: " + line);
2312 this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
2316 /// UserStreamsから受信した公式RTをイベントに変換します
2318 private FormattedEvent CreateEventFromRetweet(XElement xElm)
2320 return new FormattedEvent
2322 Eventtype = MyCommon.EVENTTYPE.Retweet,
2324 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
2325 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
2326 Username = xElm.XPathSelectElement("/user/screen_name").Value,
2327 Target = string.Format("@{0}:{1}", new[]
2329 xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
2330 WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
2332 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
2336 private void CreateEventFromJson(string content)
2338 TwitterStreamEvent eventData = null;
2341 eventData = TwitterStreamEvent.ParseJson(content);
2343 catch(SerializationException ex)
2345 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
2349 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
2352 var evt = new FormattedEvent();
2353 evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
2354 evt.Event = eventData.Event;
2355 evt.Username = eventData.Source.ScreenName;
2356 evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
2358 MyCommon.EVENTTYPE eventType;
2359 eventTable.TryGetValue(eventData.Event, out eventType);
2360 evt.Eventtype = eventType;
2362 TwitterStreamEvent<TwitterStatus> tweetEvent;
2364 switch (eventData.Event)
2366 case "access_revoked":
2367 case "access_unrevoked":
2369 case "user_suspend":
2372 if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
2374 if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
2378 return; //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
2383 evt.Target = "@" + eventData.Target.ScreenName;
2385 case "favorited_retweet":
2386 case "retweeted_retweet":
2390 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2391 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2392 evt.Id = tweetEvent.TargetObject.Id;
2394 if (SettingCommon.Instance.IsRemoveSameEvent)
2396 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2400 var tabinfo = TabInformations.GetInstance();
2403 var statusId = tweetEvent.TargetObject.Id;
2404 if (!tabinfo.Posts.TryGetValue(statusId, out post))
2407 if (eventData.Event == "favorite")
2409 var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2410 if (!favTab.Contains(post.StatusId))
2411 favTab.AddPostImmediately(post.StatusId, post.IsRead);
2413 if (tweetEvent.Source.Id == this.UserId)
2417 else if (tweetEvent.Target.Id == this.UserId)
2419 post.FavoritedCount++;
2421 if (SettingCommon.Instance.FavEventUnread)
2422 tabinfo.SetReadAllTab(post.StatusId, read: false);
2427 if (tweetEvent.Source.Id == this.UserId)
2431 else if (tweetEvent.Target.Id == this.UserId)
2433 post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2437 case "quoted_tweet":
2438 if (evt.IsMe) return;
2440 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2441 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2442 evt.Id = tweetEvent.TargetObject.Id;
2444 if (SettingCommon.Instance.IsRemoveSameEvent)
2446 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2450 case "list_member_added":
2451 case "list_member_removed":
2452 case "list_created":
2453 case "list_destroyed":
2454 case "list_updated":
2455 case "list_user_subscribed":
2456 case "list_user_unsubscribed":
2457 var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2458 evt.Target = listEvent.TargetObject.FullName;
2461 if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2465 if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2474 evt.Target = "@" + eventData.Target.ScreenName;
2475 if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2477 TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2481 evt.Target = "@" + eventData.Target.ScreenName;
2482 if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2484 TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2489 MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2492 this.StoredEvent.Insert(0, evt);
2494 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2497 private void userStream_Started()
2499 this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2502 private void userStream_Stopped()
2504 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2507 public bool UserStreamActive
2508 => this.userStream == null ? false : this.userStream.IsStreamActive;
2510 public void StartUserStream()
2512 var newStream = new TwitterUserstream(this.Api);
2514 newStream.StatusArrived += userStream_StatusArrived;
2515 newStream.Started += userStream_Started;
2516 newStream.Stopped += userStream_Stopped;
2518 newStream.Start(this.AllAtReply, this.TrackWord);
2520 var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2521 oldStream?.Dispose();
2524 public void StopUserStream()
2526 var oldStream = Interlocked.Exchange(ref this.userStream, null);
2527 oldStream?.Dispose();
2530 public void ReconnectUserStream()
2532 this.StartUserStream();
2535 private class TwitterUserstream : IDisposable
2537 public bool AllAtReplies { get; private set; }
2538 public string TrackWords { get; private set; }
2540 public bool IsStreamActive { get; private set; }
2542 public event Action<string> StatusArrived;
2543 public event Action Stopped;
2544 public event Action Started;
2546 private TwitterApi twitterApi;
2548 private Task streamTask;
2549 private CancellationTokenSource streamCts;
2551 public TwitterUserstream(TwitterApi twitterApi)
2553 this.twitterApi = twitterApi;
2556 public void Start(bool allAtReplies, string trackwords)
2558 this.AllAtReplies = allAtReplies;
2559 this.TrackWords = trackwords;
2561 var cts = new CancellationTokenSource();
2563 this.streamCts = cts;
2564 this.streamTask = Task.Run(async () =>
2568 await this.UserStreamLoop(cts.Token)
2569 .ConfigureAwait(false);
2571 catch (OperationCanceledException) { }
2577 this.streamCts?.Cancel();
2579 // streamTask の完了を待たずに IsStreamActive を false にセットする
2580 this.IsStreamActive = false;
2581 this.Stopped?.Invoke();
2584 private async Task UserStreamLoop(CancellationToken cancellationToken)
2586 TimeSpan? sleep = null;
2591 await Task.Delay(sleep.Value, cancellationToken)
2592 .ConfigureAwait(false);
2596 if (!MyCommon.IsNetworkAvailable())
2598 sleep = TimeSpan.FromSeconds(30);
2602 this.IsStreamActive = true;
2603 this.Started?.Invoke();
2607 var replies = this.AllAtReplies ? "all" : null;
2609 using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2610 .ConfigureAwait(false))
2611 using (var reader = new StreamReader(stream))
2613 while (!reader.EndOfStream)
2615 var line = await reader.ReadLineAsync()
2616 .ConfigureAwait(false);
2618 cancellationToken.ThrowIfCancellationRequested();
2620 this.StatusArrived?.Invoke(line);
2624 // キャンセルされていないのにストリームが終了した場合
2625 sleep = TimeSpan.FromSeconds(30);
2627 catch (HttpRequestException) { sleep = TimeSpan.FromSeconds(30); }
2628 catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2629 catch (OperationCanceledException)
2631 if (cancellationToken.IsCancellationRequested)
2634 // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2635 sleep = TimeSpan.FromSeconds(30);
2637 catch (Exception ex)
2639 MyCommon.ExceptionOut(ex);
2640 sleep = TimeSpan.FromSeconds(30);
2644 this.IsStreamActive = false;
2645 this.Stopped?.Invoke();
2650 private bool disposed = false;
2652 public void Dispose()
2657 this.disposed = true;
2661 this.Started = null;
2662 this.Stopped = null;
2663 this.StatusArrived = null;
2668 #region "IDisposable Support"
2669 private bool disposedValue; // 重複する呼び出しを検出するには
2672 protected virtual void Dispose(bool disposing)
2674 if (!this.disposedValue)
2678 this.StopUserStream();
2681 this.disposedValue = true;
2684 //protected Overrides void Finalize()
2686 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2688 // MyBase.Finalize()
2691 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2692 public void Dispose()
2694 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2696 GC.SuppressFinalize(this);
2701 public class PostDeletedEventArgs : EventArgs
2703 public long StatusId { get; }
2705 public PostDeletedEventArgs(long statusId)
2707 this.StatusId = statusId;
2711 public class UserStreamEventReceivedEventArgs : EventArgs
2713 public Twitter.FormattedEvent EventData { get; }
2715 public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2717 this.EventData = eventData;