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;
52 using OpenTween.Models;
56 public class Twitter : IDisposable
58 #region Regexp from twitter-text-js
60 // The code in this region code block incorporates works covered by
61 // the following copyright and permission notices:
63 // Copyright 2011 Twitter, Inc.
65 // Licensed under the Apache License, Version 2.0 (the "License"); you
66 // may not use this work except in compliance with the License. You
67 // may obtain a copy of the License in the LICENSE file, or at:
69 // http://www.apache.org/licenses/LICENSE-2.0
71 // Unless required by applicable law or agreed to in writing, software
72 // distributed under the License is distributed on an "AS IS" BASIS,
73 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
74 // implied. See the License for the specific language governing
75 // permissions and limitations under the License.
78 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";
79 private const string NON_LATIN_HASHTAG_CHARS = @"\u0400-\u04ff\u0500-\u0527\u1100-\u11ff\u3130-\u3185\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF";
80 //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";
81 private const string CJ_HASHTAG_CHARACTERS = @"\u30A1-\u30FA\u30FC\u3005\uFF66-\uFF9F\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\u3041-\u309A\u3400-\u4DBF\p{IsCJKUnifiedIdeographs}";
82 private const string HASHTAG_BOUNDARY = @"^|$|\s|「|」|。|\.|!";
83 private const string HASHTAG_ALPHA = "[a-z_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
84 private const string HASHTAG_ALPHANUMERIC = "[a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
85 private const string HASHTAG_TERMINATOR = "[^a-z0-9_" + LATIN_ACCENTS + NON_LATIN_HASHTAG_CHARS + CJ_HASHTAG_CHARACTERS + "]";
86 public const string HASHTAG = "(" + HASHTAG_BOUNDARY + ")(#|#)(" + HASHTAG_ALPHANUMERIC + "*" + HASHTAG_ALPHA + HASHTAG_ALPHANUMERIC + "*)(?=" + HASHTAG_TERMINATOR + "|" + HASHTAG_BOUNDARY + ")";
88 private const string url_valid_preceding_chars = @"(?:[^A-Za-z0-9@@$##\ufffe\ufeff\uffff\u202a-\u202e]|^)";
89 public const string url_invalid_without_protocol_preceding_chars = @"[-_./]$";
90 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";
91 private const string url_valid_domain_chars = @"[^" + url_invalid_domain_chars + "]";
92 private const string url_valid_subdomain = @"(?:(?:" + url_valid_domain_chars + @"(?:[_-]|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
93 private const string url_valid_domain_name = @"(?:(?:" + url_valid_domain_chars + @"(?:-|" + url_valid_domain_chars + @")*)?" + url_valid_domain_chars + @"\.)";
94 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]|$))";
95 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]|$))";
96 private const string url_valid_punycode = @"(?:xn--[0-9a-z]+)";
97 private const string url_valid_domain = @"(?<domain>" + url_valid_subdomain + "*" + url_valid_domain_name + "(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + ")|" + url_valid_punycode + ")";
98 public const string url_valid_ascii_domain = @"(?:(?:[a-z0-9" + LATIN_ACCENTS + @"]+)\.)+(?:" + url_valid_GTLD + "|" + url_valid_CCTLD + "|" + url_valid_punycode + ")";
99 public const string url_invalid_short_domain = "^" + url_valid_domain_name + url_valid_CCTLD + "$";
100 private const string url_valid_port_number = @"[0-9]+";
102 private const string url_valid_general_path_chars = @"[a-z0-9!*';:=+,.$/%#\[\]\-_~|&" + LATIN_ACCENTS + "]";
103 private const string url_balance_parens = @"(?:\(" + url_valid_general_path_chars + @"+\))";
104 private const string url_valid_path_ending_chars = @"(?:[+\-a-z0-9=_#/" + LATIN_ACCENTS + "]|" + url_balance_parens + ")";
105 private const string pth = "(?:" +
107 url_valid_general_path_chars + "*" +
108 "(?:" + url_balance_parens + url_valid_general_path_chars + "*)*" +
109 url_valid_path_ending_chars +
110 ")|(?:@" + url_valid_general_path_chars + "+/)" +
112 private const string qry = @"(?<query>\?[a-z0-9!?*'();:&=+$/%#\[\]\-_.,~|]*[a-z0-9_&=#/])?";
113 public const string rgUrl = @"(?<before>" + url_valid_preceding_chars + ")" +
114 "(?<url>(?<protocol>https?://)?" +
115 "(?<domain>" + url_valid_domain + ")" +
116 "(?::" + url_valid_port_number + ")?" +
117 "(?<path>/" + pth + "*)?" +
124 /// Twitter API のステータスページのURL
126 public const string ServiceAvailabilityStatusUrl = "https://status.io.watchmouse.com/7617";
129 /// ツイートへのパーマリンクURLを判定する正規表現
131 public static readonly Regex StatusUrlRegex = new Regex(@"https?://([^.]+\.)?twitter\.com/(#!/)?(?<ScreenName>[a-zA-Z0-9_]+)/status(es)?/(?<StatusId>[0-9]+)(/photo)?", RegexOptions.IgnoreCase);
134 /// FavstarやaclogなどTwitter関連サービスのパーマリンクURLからステータスIDを抽出する正規表現
136 public static readonly Regex ThirdPartyStatusUrlRegex = new Regex(@"https?://(?:[^.]+\.)?(?:
137 favstar\.fm/users/[a-zA-Z0-9_]+/status/ # Favstar
138 | favstar\.fm/t/ # Favstar (short)
139 | aclog\.koba789\.com/i/ # aclog
140 | frtrt\.net/solo_status\.php\?status= # RtRT
141 )(?<StatusId>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
144 /// DM送信かどうかを判定する正規表現
146 public static readonly Regex DMSendTextRegex = new Regex(@"^DM? +(?<id>[a-zA-Z0-9_]+) +(?<body>.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
148 public TwitterApi Api { get; }
149 public TwitterConfiguration Configuration { get; private set; }
151 delegate void GetIconImageDelegate(PostClass post);
152 private readonly object LockObj = new object();
153 private ISet<long> followerId = new HashSet<long>();
154 private bool _GetFollowerResult = false;
155 private long[] noRTId = new long[0];
156 private bool _GetNoRetweetResult = false;
159 private string _uname;
161 private bool _readOwnPost;
162 private List<string> _hashList = new List<string>();
164 //max_idで古い発言を取得するために保持(lists分は個別タブで管理)
165 private long minHomeTimeline = long.MaxValue;
166 private long minMentions = long.MaxValue;
167 private long minDirectmessage = long.MaxValue;
168 private long minDirectmessageSent = long.MaxValue;
170 //private FavoriteQueue favQueue;
172 //private List<PostClass> _deletemessages = new List<PostClass>();
174 public Twitter() : this(new TwitterApi())
178 public Twitter(TwitterApi api)
181 this.Configuration = TwitterConfiguration.DefaultConfiguration();
184 public TwitterApiAccessLevel AccessLevel
188 return MyCommon.TwitterApiInfo.AccessLevel;
192 protected void ResetApiStatus()
194 MyCommon.TwitterApiInfo.Reset();
197 public void ClearAuthInfo()
199 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
200 this.ResetApiStatus();
204 public void VerifyCredentials()
208 this.VerifyCredentialsAsync().Wait();
210 catch (AggregateException ex) when (ex.InnerException is WebApiException)
212 throw new WebApiException(ex.InnerException.Message, ex);
216 public async Task VerifyCredentialsAsync()
218 var user = await this.Api.AccountVerifyCredentials()
219 .ConfigureAwait(false);
221 this.UpdateUserStats(user);
224 public void Initialize(string token, string tokenSecret, string username, long userId)
227 if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(tokenSecret) || string.IsNullOrEmpty(username))
229 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
231 this.ResetApiStatus();
232 this.Api.Initialize(token, tokenSecret, userId, username);
233 _uname = username.ToLowerInvariant();
234 if (SettingCommon.Instance.UserstreamStartup) this.ReconnectUserStream();
237 public string PreProcessUrl(string orgData)
241 //var IDNConveter = new IdnMapping();
242 var href = "<a href=\"";
246 if (orgData.IndexOf(href, posl2, StringComparison.Ordinal) > -1)
250 posl1 = orgData.IndexOf(href, posl2, StringComparison.Ordinal);
251 posl1 += href.Length;
252 posl2 = orgData.IndexOf("\"", posl1, StringComparison.Ordinal);
253 urlStr = orgData.Substring(posl1, posl2 - posl1);
255 if (!urlStr.StartsWith("http://", StringComparison.Ordinal)
256 && !urlStr.StartsWith("https://", StringComparison.Ordinal)
257 && !urlStr.StartsWith("ftp://", StringComparison.Ordinal))
262 var replacedUrl = MyCommon.IDNEncode(urlStr);
263 if (replacedUrl == null) continue;
264 if (replacedUrl == urlStr) continue;
266 orgData = orgData.Replace("<a href=\"" + urlStr, "<a href=\"" + replacedUrl);
277 private string GetPlainText(string orgData)
279 return WebUtility.HtmlDecode(Regex.Replace(orgData, "(?<tagStart><a [^>]+>)(?<text>[^<]+)(?<tagEnd></a>)", "${text}"));
282 // htmlの簡易サニタイズ(詳細表示に不要なタグの除去)
284 private string SanitizeHtml(string orgdata)
286 var retdata = orgdata;
288 retdata = Regex.Replace(retdata, "<(script|object|applet|image|frameset|fieldset|legend|style).*" +
289 "</(script|object|applet|image|frameset|fieldset|legend|style)>", "", RegexOptions.IgnoreCase);
291 retdata = Regex.Replace(retdata, "<(frame|link|iframe|img)>", "", RegexOptions.IgnoreCase);
296 private string AdjustHtml(string orgData)
298 var retStr = orgData;
299 //var m = Regex.Match(retStr, "<a [^>]+>[#|#](?<1>[a-zA-Z0-9_]+)</a>");
304 // _hashList.Add("#" + m.Groups(1).Value);
308 retStr = Regex.Replace(retStr, "<a [^>]*href=\"/", "<a href=\"https://twitter.com/");
309 retStr = retStr.Replace("<a href=", "<a target=\"_self\" href=");
310 retStr = Regex.Replace(retStr, @"(\r\n?|\n)", "<br>"); // CRLF, CR, LF は全て <br> に置換する
312 //半角スペースを置換(Thanks @anis774)
316 ret = EscapeSpace(ref retStr);
319 return SanitizeHtml(retStr);
322 private bool EscapeSpace(ref string html)
324 //半角スペースを置換(Thanks @anis774)
326 for (int i = 0; i < html.Length; i++)
337 if ((!isTag) && (html[i] == ' '))
339 html = html.Remove(i, 1);
340 html = html.Insert(i, " ");
347 private struct PostInfo
349 public string CreatedAt;
352 public string UserId;
353 public PostInfo(string Created, string IdStr, string txt, string uid)
360 public bool Equals(PostInfo dst)
362 if (this.CreatedAt == dst.CreatedAt && this.Id == dst.Id && this.Text == dst.Text && this.UserId == dst.UserId)
373 static private PostInfo _prev = new PostInfo("", "", "", "");
374 private bool IsPostRestricted(TwitterStatus status)
376 var _current = new PostInfo("", "", "", "");
378 _current.CreatedAt = status.CreatedAt;
379 _current.Id = status.IdStr;
380 if (status.Text == null)
386 _current.Text = status.Text;
388 _current.UserId = status.User.IdStr;
390 if (_current.Equals(_prev))
394 _prev.CreatedAt = _current.CreatedAt;
395 _prev.Id = _current.Id;
396 _prev.Text = _current.Text;
397 _prev.UserId = _current.UserId;
402 public async Task PostStatus(string postStr, long? reply_to, IReadOnlyList<long> mediaIds = null)
404 this.CheckAccountState();
406 if (mediaIds == null &&
407 Twitter.DMSendTextRegex.IsMatch(postStr))
409 await this.SendDirectMessage(postStr)
410 .ConfigureAwait(false);
414 var response = await this.Api.StatusesUpdate(postStr, reply_to, mediaIds)
415 .ConfigureAwait(false);
417 var status = await response.LoadJsonAsync()
418 .ConfigureAwait(false);
420 this.UpdateUserStats(status.User);
422 if (IsPostRestricted(status))
424 throw new WebApiException("OK:Delaying?");
428 public async Task PostStatusWithMultipleMedia(string postStr, long? reply_to, IMediaItem[] mediaItems)
430 this.CheckAccountState();
432 if (Twitter.DMSendTextRegex.IsMatch(postStr))
434 await this.SendDirectMessage(postStr)
435 .ConfigureAwait(false);
439 if (mediaItems.Length == 0)
440 throw new WebApiException("Err:Invalid Files!");
442 var uploadTasks = from m in mediaItems
443 select this.UploadMedia(m);
445 var mediaIds = await Task.WhenAll(uploadTasks)
446 .ConfigureAwait(false);
448 await this.PostStatus(postStr, reply_to, mediaIds)
449 .ConfigureAwait(false);
452 public async Task<long> UploadMedia(IMediaItem item)
454 this.CheckAccountState();
456 var response = await this.Api.MediaUpload(item)
457 .ConfigureAwait(false);
459 var media = await response.LoadJsonAsync()
460 .ConfigureAwait(false);
462 return media.MediaId;
465 public async Task SendDirectMessage(string postStr)
467 this.CheckAccountState();
468 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
470 var mc = Twitter.DMSendTextRegex.Match(postStr);
472 var response = await this.Api.DirectMessagesNew(mc.Groups["body"].Value, mc.Groups["id"].Value)
473 .ConfigureAwait(false);
475 var dm = await response.LoadJsonAsync()
476 .ConfigureAwait(false);
478 this.UpdateUserStats(dm.Sender);
481 public async Task PostRetweet(long id, bool read)
483 this.CheckAccountState();
487 var post = TabInformations.GetInstance()[id];
490 throw new WebApiException("Err:Target isn't found.");
492 if (TabInformations.GetInstance()[id].RetweetedId != null)
494 target = TabInformations.GetInstance()[id].RetweetedId.Value; //再RTの場合は元発言をRT
497 var response = await this.Api.StatusesRetweet(target)
498 .ConfigureAwait(false);
500 var status = await response.LoadJsonAsync()
501 .ConfigureAwait(false);
504 post = CreatePostsFromStatusData(status);
506 throw new WebApiException("Invalid Json!");
511 if (TabInformations.GetInstance().ContainsKey(post.StatusId))
515 if (post.RetweetedId == null)
516 throw new WebApiException("Invalid Json!");
522 if (_readOwnPost) post.IsRead = true;
525 TabInformations.GetInstance().AddPost(post);
528 public string Username
529 => this.Api.CurrentScreenName;
532 => this.Api.CurrentUserId;
534 private static MyCommon.ACCOUNT_STATE _accountState = MyCommon.ACCOUNT_STATE.Valid;
535 public static MyCommon.ACCOUNT_STATE AccountState
539 return _accountState;
543 _accountState = value;
547 public bool RestrictFavCheck { get; set; }
550 public void GetTweenBinary(string strVer)
555 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/Tween" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
556 Path.Combine(MyCommon.settingPath, "TweenNew.exe")))
558 throw new WebApiException("Err:Download failed");
561 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, "en")))
563 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, "en"));
565 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenResEn" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
566 Path.Combine(Path.Combine(MyCommon.settingPath, "en"), "Tween.resourcesNew.dll")))
568 throw new WebApiException("Err:Download failed");
570 //その他言語圏のリソース。取得失敗しても継続
573 if (!Thread.CurrentThread.CurrentUICulture.IsNeutralCulture)
575 var idx = Thread.CurrentThread.CurrentUICulture.Name.LastIndexOf('-');
578 curCul = Thread.CurrentThread.CurrentUICulture.Name.Substring(0, idx);
582 curCul = Thread.CurrentThread.CurrentUICulture.Name;
587 curCul = Thread.CurrentThread.CurrentUICulture.Name;
589 if (!string.IsNullOrEmpty(curCul) && curCul != "en" && curCul != "ja")
591 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul)))
593 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul));
595 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
596 Path.Combine(Path.Combine(MyCommon.settingPath, curCul), "Tween.resourcesNew.dll")))
598 //return "Err:Download failed";
603 if (!Thread.CurrentThread.CurrentCulture.IsNeutralCulture)
605 var idx = Thread.CurrentThread.CurrentCulture.Name.LastIndexOf('-');
608 curCul2 = Thread.CurrentThread.CurrentCulture.Name.Substring(0, idx);
612 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
617 curCul2 = Thread.CurrentThread.CurrentCulture.Name;
619 if (!string.IsNullOrEmpty(curCul2) && curCul2 != "en" && curCul2 != curCul)
621 if (!Directory.Exists(Path.Combine(MyCommon.settingPath, curCul2)))
623 Directory.CreateDirectory(Path.Combine(MyCommon.settingPath, curCul2));
625 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenRes" + curCul2 + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
626 Path.Combine(Path.Combine(MyCommon.settingPath, curCul2), "Tween.resourcesNew.dll")))
628 //return "Err:Download failed";
633 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenUp3.gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
634 Path.Combine(MyCommon.settingPath, "TweenUp3.exe")))
636 throw new WebApiException("Err:Download failed");
639 if (!(new HttpVarious()).GetDataToFile("http://tween.sourceforge.jp/TweenDll" + strVer + ".gz?" + DateTime.Now.ToString("yyMMddHHmmss") + Environment.TickCount.ToString(),
640 Path.Combine(MyCommon.settingPath, "TweenNew.XmlSerializers.dll")))
642 throw new WebApiException("Err:Download failed");
647 throw new WebApiException("Err:Download failed", ex);
652 public bool ReadOwnPost
660 _readOwnPost = value;
664 public int FollowersCount { get; private set; }
665 public int FriendsCount { get; private set; }
666 public int StatusesCount { get; private set; }
667 public string Location { get; private set; } = "";
668 public string Bio { get; private set; } = "";
670 /// <summary>ユーザーのフォロワー数などの情報を更新します</summary>
671 private void UpdateUserStats(TwitterUser self)
673 this.FollowersCount = self.FollowersCount;
674 this.FriendsCount = self.FriendsCount;
675 this.StatusesCount = self.StatusesCount;
676 this.Location = self.Location;
677 this.Bio = self.Description;
681 /// 渡された取得件数がWORKERTYPEに応じた取得可能範囲に収まっているか検証する
683 public static bool VerifyApiResultCount(MyCommon.WORKERTYPE type, int count)
685 return count >= 20 && count <= GetMaxApiResultCount(type);
689 /// 渡された取得件数が更新時の取得可能範囲に収まっているか検証する
691 public static bool VerifyMoreApiResultCount(int count)
693 return count >= 20 && count <= 200;
697 /// 渡された取得件数が起動時の取得可能範囲に収まっているか検証する
699 public static bool VerifyFirstApiResultCount(int count)
701 return count >= 20 && count <= 200;
705 /// WORKERTYPEに応じた取得可能な最大件数を取得する
707 public static int GetMaxApiResultCount(MyCommon.WORKERTYPE type)
709 // 参照: REST APIs - 各endpointのcountパラメータ
710 // https://dev.twitter.com/rest/public
713 case MyCommon.WORKERTYPE.Timeline:
714 case MyCommon.WORKERTYPE.Reply:
715 case MyCommon.WORKERTYPE.UserTimeline:
716 case MyCommon.WORKERTYPE.Favorites:
717 case MyCommon.WORKERTYPE.DirectMessegeRcv:
718 case MyCommon.WORKERTYPE.DirectMessegeSnt:
719 case MyCommon.WORKERTYPE.List: // 不明
722 case MyCommon.WORKERTYPE.PublicSearch:
726 throw new InvalidOperationException("Invalid type: " + type);
731 /// WORKERTYPEに応じた取得件数を取得する
733 public static int GetApiResultCount(MyCommon.WORKERTYPE type, bool more, bool startup)
735 if (type == MyCommon.WORKERTYPE.DirectMessegeRcv ||
736 type == MyCommon.WORKERTYPE.DirectMessegeSnt)
741 if (SettingCommon.Instance.UseAdditionalCount)
745 case MyCommon.WORKERTYPE.Favorites:
746 if (SettingCommon.Instance.FavoritesCountApi != 0)
747 return SettingCommon.Instance.FavoritesCountApi;
749 case MyCommon.WORKERTYPE.List:
750 if (SettingCommon.Instance.ListCountApi != 0)
751 return SettingCommon.Instance.ListCountApi;
753 case MyCommon.WORKERTYPE.PublicSearch:
754 if (SettingCommon.Instance.SearchCountApi != 0)
755 return SettingCommon.Instance.SearchCountApi;
757 case MyCommon.WORKERTYPE.UserTimeline:
758 if (SettingCommon.Instance.UserTimelineCountApi != 0)
759 return SettingCommon.Instance.UserTimelineCountApi;
762 if (more && SettingCommon.Instance.MoreCountApi != 0)
764 return Math.Min(SettingCommon.Instance.MoreCountApi, GetMaxApiResultCount(type));
766 if (startup && SettingCommon.Instance.FirstCountApi != 0 && type != MyCommon.WORKERTYPE.Reply)
768 return Math.Min(SettingCommon.Instance.FirstCountApi, GetMaxApiResultCount(type));
773 var count = SettingCommon.Instance.CountApi;
775 if (type == MyCommon.WORKERTYPE.Reply)
776 count = SettingCommon.Instance.CountApiReply;
778 return Math.Min(count, GetMaxApiResultCount(type));
781 public async Task GetTimelineApi(bool read, MyCommon.WORKERTYPE gType, bool more, bool startup)
783 this.CheckAccountState();
785 var count = GetApiResultCount(gType, more, startup);
787 TwitterStatus[] statuses;
788 if (gType == MyCommon.WORKERTYPE.Timeline)
792 statuses = await this.Api.StatusesHomeTimeline(count, maxId: this.minHomeTimeline)
793 .ConfigureAwait(false);
797 statuses = await this.Api.StatusesHomeTimeline(count)
798 .ConfigureAwait(false);
805 statuses = await this.Api.StatusesMentionsTimeline(count, maxId: this.minMentions)
806 .ConfigureAwait(false);
810 statuses = await this.Api.StatusesMentionsTimeline(count)
811 .ConfigureAwait(false);
815 var minimumId = CreatePostsFromJson(statuses, gType, null, read);
817 if (minimumId != null)
819 if (gType == MyCommon.WORKERTYPE.Timeline)
820 this.minHomeTimeline = minimumId.Value;
822 this.minMentions = minimumId.Value;
826 public async Task GetUserTimelineApi(bool read, string userName, UserTimelineTabModel tab, bool more)
828 this.CheckAccountState();
830 var count = GetApiResultCount(MyCommon.WORKERTYPE.UserTimeline, more, false);
832 TwitterStatus[] statuses;
833 if (string.IsNullOrEmpty(userName))
835 var target = tab.ScreenName;
836 if (string.IsNullOrEmpty(target)) return;
838 statuses = await this.Api.StatusesUserTimeline(userName, count)
839 .ConfigureAwait(false);
845 statuses = await this.Api.StatusesUserTimeline(userName, count, maxId: tab.OldestId)
846 .ConfigureAwait(false);
850 statuses = await this.Api.StatusesUserTimeline(userName, count)
851 .ConfigureAwait(false);
855 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.UserTimeline, tab, read);
857 if (minimumId != null)
858 tab.OldestId = minimumId.Value;
861 public async Task<PostClass> GetStatusApi(bool read, long id)
863 this.CheckAccountState();
865 var status = await this.Api.StatusesShow(id)
866 .ConfigureAwait(false);
868 var item = CreatePostsFromStatusData(status);
870 throw new WebApiException("Err:Can't create post");
873 if (item.IsMe && !read && _readOwnPost) item.IsRead = true;
878 public async Task GetStatusApi(bool read, long id, TabModel tab)
880 var post = await this.GetStatusApi(read, id)
881 .ConfigureAwait(false);
883 //非同期アイコン取得&StatusDictionaryに追加
884 if (tab != null && tab.IsInnerStorageTabType)
885 tab.AddPostQueue(post);
887 TabInformations.GetInstance().AddPost(post);
890 private PostClass CreatePostsFromStatusData(TwitterStatus status)
892 return CreatePostsFromStatusData(status, false);
895 private PostClass CreatePostsFromStatusData(TwitterStatus status, bool favTweet)
897 var post = new PostClass();
898 TwitterEntities entities;
901 post.StatusId = status.Id;
902 if (status.RetweetedStatus != null)
904 var retweeted = status.RetweetedStatus;
906 post.CreatedAt = MyCommon.DateTimeParse(retweeted.CreatedAt);
909 post.RetweetedId = retweeted.Id;
911 post.TextFromApi = retweeted.Text;
912 entities = retweeted.MergedEntities;
913 sourceHtml = retweeted.Source;
915 post.InReplyToStatusId = retweeted.InReplyToStatusId;
916 post.InReplyToUser = retweeted.InReplyToScreenName;
917 post.InReplyToUserId = status.InReplyToUserId;
926 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
927 post.IsFav = tc.Contains(retweeted.Id);
930 if (retweeted.Coordinates != null)
931 post.PostGeo = new PostClass.StatusGeo(retweeted.Coordinates.Coordinates[0], retweeted.Coordinates.Coordinates[1]);
934 var user = retweeted.User;
936 if (user == null || user.ScreenName == null || status.User.ScreenName == null) return null;
938 post.UserId = user.Id;
939 post.ScreenName = user.ScreenName;
940 post.Nickname = user.Name.Trim();
941 post.ImageUrl = user.ProfileImageUrlHttps;
942 post.IsProtect = user.Protected;
945 post.RetweetedBy = status.User.ScreenName;
946 post.RetweetedByUserId = status.User.Id;
947 post.IsMe = post.RetweetedBy.ToLowerInvariant().Equals(_uname);
951 post.CreatedAt = MyCommon.DateTimeParse(status.CreatedAt);
953 post.TextFromApi = status.Text;
954 entities = status.MergedEntities;
955 sourceHtml = status.Source;
956 post.InReplyToStatusId = status.InReplyToStatusId;
957 post.InReplyToUser = status.InReplyToScreenName;
958 post.InReplyToUserId = status.InReplyToUserId;
967 var tc = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
968 post.IsFav = tc.Contains(post.StatusId) && TabInformations.GetInstance()[post.StatusId].IsFav;
971 if (status.Coordinates != null)
972 post.PostGeo = new PostClass.StatusGeo(status.Coordinates.Coordinates[0], status.Coordinates.Coordinates[1]);
975 var user = status.User;
977 if (user == null || user.ScreenName == null) return null;
979 post.UserId = user.Id;
980 post.ScreenName = user.ScreenName;
981 post.Nickname = user.Name.Trim();
982 post.ImageUrl = user.ProfileImageUrlHttps;
983 post.IsProtect = user.Protected;
984 post.IsMe = post.ScreenName.ToLowerInvariant().Equals(_uname);
987 string textFromApi = post.TextFromApi;
988 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, entities, post.Media);
989 post.TextFromApi = textFromApi;
990 post.TextFromApi = this.ReplaceTextFromApi(post.TextFromApi, entities);
991 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
992 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
994 post.QuoteStatusIds = GetQuoteTweetStatusIds(entities)
995 .Where(x => x != post.StatusId && x != post.RetweetedId)
996 .Distinct().ToArray();
998 post.ExpandedUrls = entities.OfType<TwitterEntityUrl>()
999 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1003 var source = ParseSource(sourceHtml);
1004 post.Source = source.Item1;
1005 post.SourceUri = source.Item2;
1007 post.IsReply = post.ReplyToList.Contains(_uname);
1008 post.IsExcludeReply = false;
1016 if (followerId.Count > 0) post.IsOwl = !followerId.Contains(post.UserId);
1024 /// ツイートに含まれる引用ツイートのURLからステータスIDを抽出
1026 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<TwitterEntity> entities)
1028 var urls = entities.OfType<TwitterEntityUrl>().Select(x => x.ExpandedUrl);
1030 return GetQuoteTweetStatusIds(urls);
1033 public static IEnumerable<long> GetQuoteTweetStatusIds(IEnumerable<string> urls)
1035 foreach (var url in urls)
1037 var match = Twitter.StatusUrlRegex.Match(url);
1041 if (long.TryParse(match.Groups["StatusId"].Value, out statusId))
1042 yield return statusId;
1047 private long? CreatePostsFromJson(TwitterStatus[] items, MyCommon.WORKERTYPE gType, TabModel tab, bool read)
1049 long? minimumId = null;
1051 foreach (var status in items)
1053 PostClass post = null;
1054 post = CreatePostsFromStatusData(status);
1055 if (post == null) continue;
1057 if (minimumId == null || minimumId.Value > post.StatusId)
1058 minimumId = post.StatusId;
1065 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1069 if (tab.Contains(post.StatusId)) continue;
1074 if (gType != MyCommon.WORKERTYPE.UserTimeline &&
1075 post.RetweetedByUserId != null && this.noRTId.Contains(post.RetweetedByUserId.Value)) continue;
1078 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1080 //非同期アイコン取得&StatusDictionaryに追加
1081 if (tab != null && tab.IsInnerStorageTabType)
1082 tab.AddPostQueue(post);
1084 TabInformations.GetInstance().AddPost(post);
1090 private long? CreatePostsFromSearchJson(TwitterSearchResult items, TabModel tab, bool read, int count, bool more)
1092 long? minimumId = null;
1094 foreach (var result in items.Statuses)
1096 var post = CreatePostsFromStatusData(result);
1100 if (minimumId == null || minimumId.Value > post.StatusId)
1101 minimumId = post.StatusId;
1103 if (!more && post.StatusId > tab.SinceId) tab.SinceId = post.StatusId;
1109 if (TabInformations.GetInstance().ContainsKey(post.StatusId)) continue;
1113 if (tab.Contains(post.StatusId)) continue;
1118 if ((post.IsMe && !read) && this._readOwnPost) post.IsRead = true;
1120 //非同期アイコン取得&StatusDictionaryに追加
1121 if (tab != null && tab.IsInnerStorageTabType)
1122 tab.AddPostQueue(post);
1124 TabInformations.GetInstance().AddPost(post);
1130 private void CreateFavoritePostsFromJson(TwitterStatus[] item, bool read)
1132 var favTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.Favorites);
1134 foreach (var status in item)
1139 if (favTab.Contains(status.Id)) continue;
1142 var post = CreatePostsFromStatusData(status, true);
1143 if (post == null) continue;
1147 TabInformations.GetInstance().AddPost(post);
1151 public async Task GetListStatus(bool read, ListTimelineTabModel tab, bool more, bool startup)
1153 var count = GetApiResultCount(MyCommon.WORKERTYPE.List, more, startup);
1155 TwitterStatus[] statuses;
1158 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, maxId: tab.OldestId, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
1159 .ConfigureAwait(false);
1163 statuses = await this.Api.ListsStatuses(tab.ListInfo.Id, count, includeRTs: SettingCommon.Instance.IsListsIncludeRts)
1164 .ConfigureAwait(false);
1167 var minimumId = CreatePostsFromJson(statuses, MyCommon.WORKERTYPE.List, tab, read);
1169 if (minimumId != null)
1170 tab.OldestId = minimumId.Value;
1174 /// startStatusId からリプライ先の発言を辿る。発言は posts 以外からは検索しない。
1176 /// <returns>posts の中から検索されたリプライチェインの末端</returns>
1177 internal static PostClass FindTopOfReplyChain(IDictionary<Int64, PostClass> posts, Int64 startStatusId)
1179 if (!posts.ContainsKey(startStatusId))
1180 throw new ArgumentException("startStatusId (" + startStatusId + ") が posts の中から見つかりませんでした。", nameof(startStatusId));
1182 var nextPost = posts[startStatusId];
1183 while (nextPost.InReplyToStatusId != null)
1185 if (!posts.ContainsKey(nextPost.InReplyToStatusId.Value))
1187 nextPost = posts[nextPost.InReplyToStatusId.Value];
1193 public async Task GetRelatedResult(bool read, RelatedPostsTabModel tab)
1195 var targetPost = tab.TargetPost;
1196 var relPosts = new Dictionary<Int64, PostClass>();
1197 if (targetPost.TextFromApi.Contains("@") && targetPost.InReplyToStatusId == null)
1200 var p = TabInformations.GetInstance()[targetPost.StatusId];
1201 if (p != null && p.InReplyToStatusId != null)
1207 p = await this.GetStatusApi(read, targetPost.StatusId)
1208 .ConfigureAwait(false);
1212 relPosts.Add(targetPost.StatusId, targetPost);
1214 Exception lastException = null;
1216 // in_reply_to_status_id を使用してリプライチェインを辿る
1217 var nextPost = FindTopOfReplyChain(relPosts, targetPost.StatusId);
1219 while (nextPost.InReplyToStatusId != null && loopCount++ <= 20)
1221 var inReplyToId = nextPost.InReplyToStatusId.Value;
1223 var inReplyToPost = TabInformations.GetInstance()[inReplyToId];
1224 if (inReplyToPost == null)
1228 inReplyToPost = await this.GetStatusApi(read, inReplyToId)
1229 .ConfigureAwait(false);
1231 catch (WebApiException ex)
1238 relPosts.Add(inReplyToPost.StatusId, inReplyToPost);
1240 nextPost = FindTopOfReplyChain(relPosts, nextPost.StatusId);
1243 //MRTとかに対応のためツイート内にあるツイートを指すURLを取り込む
1244 var text = targetPost.Text;
1245 var ma = Twitter.StatusUrlRegex.Matches(text).Cast<Match>()
1246 .Concat(Twitter.ThirdPartyStatusUrlRegex.Matches(text).Cast<Match>());
1247 foreach (var _match in ma)
1250 if (Int64.TryParse(_match.Groups["StatusId"].Value, out _statusId))
1252 if (relPosts.ContainsKey(_statusId))
1255 var p = TabInformations.GetInstance()[_statusId];
1260 p = await this.GetStatusApi(read, _statusId)
1261 .ConfigureAwait(false);
1263 catch (WebApiException ex)
1271 relPosts.Add(p.StatusId, p);
1275 relPosts.Values.ToList().ForEach(p =>
1277 if (p.IsMe && !read && this._readOwnPost)
1282 tab.AddPostQueue(p);
1285 if (lastException != null)
1286 throw new WebApiException(lastException.Message, lastException);
1289 public async Task GetSearch(bool read, PublicSearchTabModel tab, bool more)
1291 var count = GetApiResultCount(MyCommon.WORKERTYPE.PublicSearch, more, false);
1294 long? sinceId = null;
1297 maxId = tab.OldestId - 1;
1301 sinceId = tab.SinceId;
1304 var searchResult = await this.Api.SearchTweets(tab.SearchWords, tab.SearchLang, count, maxId, sinceId)
1305 .ConfigureAwait(false);
1307 if (!TabInformations.GetInstance().ContainsTab(tab))
1310 var minimumId = this.CreatePostsFromSearchJson(searchResult, tab, read, count, more);
1312 if (minimumId != null)
1313 tab.OldestId = minimumId.Value;
1316 private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read)
1318 foreach (var message in item)
1320 var post = new PostClass();
1323 post.StatusId = message.Id;
1324 if (gType != MyCommon.WORKERTYPE.UserStream)
1326 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1328 if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId;
1332 if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId;
1339 if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue;
1343 post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt);
1345 var textFromApi = message.Text;
1347 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media);
1348 post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities);
1349 post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi);
1350 post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661");
1353 post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray();
1355 post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>()
1356 .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl))
1361 if (gType == MyCommon.WORKERTYPE.UserStream)
1363 if (this.Api.CurrentUserId == message.Recipient.Id)
1365 user = message.Sender;
1371 user = message.Recipient;
1378 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1380 user = message.Sender;
1386 user = message.Recipient;
1392 post.UserId = user.Id;
1393 post.ScreenName = user.ScreenName;
1394 post.Nickname = user.Name.Trim();
1395 post.ImageUrl = user.ProfileImageUrlHttps;
1396 post.IsProtect = user.Protected;
1400 MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name);
1401 MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)");
1406 if (post.IsMe && !read && _readOwnPost) post.IsRead = true;
1407 post.IsReply = false;
1408 post.IsExcludeReply = false;
1411 var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage);
1412 dmTab.AddPostQueue(post);
1416 public async Task GetDirectMessageApi(bool read, MyCommon.WORKERTYPE gType, bool more)
1418 this.CheckAccountState();
1419 this.CheckAccessLevel(TwitterApiAccessLevel.ReadWriteAndDirectMessage);
1421 var count = GetApiResultCount(gType, more, false);
1423 TwitterDirectMessage[] messages;
1424 if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv)
1428 messages = await this.Api.DirectMessagesRecv(count, maxId: this.minDirectmessage)
1429 .ConfigureAwait(false);
1433 messages = await this.Api.DirectMessagesRecv(count)
1434 .ConfigureAwait(false);
1441 messages = await this.Api.DirectMessagesSent(count, maxId: this.minDirectmessageSent)
1442 .ConfigureAwait(false);
1446 messages = await this.Api.DirectMessagesSent(count)
1447 .ConfigureAwait(false);
1451 CreateDirectMessagesFromJson(messages, gType, read);
1454 public async Task GetFavoritesApi(bool read, bool more)
1456 this.CheckAccountState();
1458 var count = GetApiResultCount(MyCommon.WORKERTYPE.Favorites, more, false);
1460 var statuses = await this.Api.FavoritesList(count)
1461 .ConfigureAwait(false);
1463 CreateFavoritePostsFromJson(statuses, read);
1466 private string ReplaceTextFromApi(string text, TwitterEntities entities)
1468 if (entities != null)
1470 if (entities.Urls != null)
1472 foreach (var m in entities.Urls)
1474 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1477 if (entities.Media != null)
1479 foreach (var m in entities.Media)
1481 if (m.AltText != null)
1483 text = text.Replace(m.Url, string.Format(Properties.Resources.ImageAltText, m.AltText));
1487 if (!string.IsNullOrEmpty(m.DisplayUrl)) text = text.Replace(m.Url, m.DisplayUrl);
1498 /// <exception cref="WebApiException"/>
1499 public async Task RefreshFollowerIds()
1501 if (MyCommon._endingFlag) return;
1504 var newFollowerIds = new HashSet<long>();
1507 var ret = await this.Api.FollowersIds(cursor)
1508 .ConfigureAwait(false);
1510 if (ret.Ids == null)
1511 throw new WebApiException("ret.ids == null");
1513 newFollowerIds.UnionWith(ret.Ids);
1514 cursor = ret.NextCursor;
1515 } while (cursor != 0);
1517 this.followerId = newFollowerIds;
1518 TabInformations.GetInstance().RefreshOwl(this.followerId);
1520 this._GetFollowerResult = true;
1523 public bool GetFollowersSuccess
1527 return _GetFollowerResult;
1532 /// RT 非表示ユーザーを更新します
1534 /// <exception cref="WebApiException"/>
1535 public async Task RefreshNoRetweetIds()
1537 if (MyCommon._endingFlag) return;
1539 this.noRTId = await this.Api.NoRetweetIds()
1540 .ConfigureAwait(false);
1542 this._GetNoRetweetResult = true;
1545 public bool GetNoRetweetSuccess
1549 return _GetNoRetweetResult;
1554 /// t.co の文字列長などの設定情報を更新します
1556 /// <exception cref="WebApiException"/>
1557 public async Task RefreshConfiguration()
1559 this.Configuration = await this.Api.Configuration()
1560 .ConfigureAwait(false);
1563 public async Task GetListsApi()
1565 this.CheckAccountState();
1567 var ownedLists = await TwitterLists.GetAllItemsAsync(x => this.Api.ListsOwnerships(this.Username, cursor: x))
1568 .ConfigureAwait(false);
1570 var subscribedLists = await TwitterLists.GetAllItemsAsync(x => this.Api.ListsSubscriptions(this.Username, cursor: x))
1571 .ConfigureAwait(false);
1573 TabInformations.GetInstance().SubscribableLists = Enumerable.Concat(ownedLists, subscribedLists)
1574 .Select(x => new ListElement(x, this))
1578 public async Task DeleteList(long listId)
1580 await this.Api.ListsDestroy(listId)
1582 .ConfigureAwait(false);
1584 var tabinfo = TabInformations.GetInstance();
1586 tabinfo.SubscribableLists = tabinfo.SubscribableLists
1587 .Where(x => x.Id != listId)
1591 public async Task<ListElement> EditList(long listId, string new_name, bool isPrivate, string description)
1593 var response = await this.Api.ListsUpdate(listId, new_name, description, isPrivate)
1594 .ConfigureAwait(false);
1596 var list = await response.LoadJsonAsync()
1597 .ConfigureAwait(false);
1599 return new ListElement(list, this);
1602 public async Task<long> GetListMembers(long listId, List<UserInfo> lists, long cursor)
1604 this.CheckAccountState();
1606 var users = await this.Api.ListsMembers(listId, cursor)
1607 .ConfigureAwait(false);
1609 Array.ForEach(users.Users, u => lists.Add(new UserInfo(u)));
1611 return users.NextCursor;
1614 public async Task CreateListApi(string listName, bool isPrivate, string description)
1616 this.CheckAccountState();
1618 var response = await this.Api.ListsCreate(listName, description, isPrivate)
1619 .ConfigureAwait(false);
1621 var list = await response.LoadJsonAsync()
1622 .ConfigureAwait(false);
1624 TabInformations.GetInstance().SubscribableLists.Add(new ListElement(list, this));
1627 public async Task<bool> ContainsUserAtList(long listId, string user)
1629 this.CheckAccountState();
1633 await this.Api.ListsMembersShow(listId, user)
1634 .ConfigureAwait(false);
1638 catch (TwitterApiException ex)
1639 when (ex.ErrorResponse.Errors.Any(x => x.Code == TwitterErrorCode.NotFound))
1645 public string CreateHtmlAnchor(string text, List<string> AtList, TwitterEntities entities, List<MediaInfo> media)
1647 if (entities != null)
1649 if (entities.Hashtags != null)
1653 this._hashList.AddRange(entities.Hashtags.Select(x => "#" + x.Text));
1656 if (entities.UserMentions != null)
1658 foreach (var ent in entities.UserMentions)
1660 var screenName = ent.ScreenName.ToLowerInvariant();
1661 if (!AtList.Contains(screenName))
1662 AtList.Add(screenName);
1665 if (entities.Media != null)
1669 foreach (var ent in entities.Media)
1671 if (!media.Any(x => x.Url == ent.MediaUrl))
1673 if (ent.VideoInfo != null &&
1674 ent.Type == "animated_gif" || ent.Type == "video")
1676 //var videoUrl = ent.VideoInfo.Variants
1677 // .Where(v => v.ContentType == "video/mp4")
1678 // .OrderByDescending(v => v.Bitrate)
1679 // .Select(v => v.Url).FirstOrDefault();
1680 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, ent.ExpandedUrl));
1683 media.Add(new MediaInfo(ent.MediaUrl, ent.AltText, videoUrl: null));
1690 // PostClass.ExpandedUrlInfo を使用して非同期に URL 展開を行うためここでは expanded_url を使用しない
1691 text = TweetFormatter.AutoLinkHtml(text, entities, keepTco: true);
1693 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>");
1694 text = PreProcessUrl(text); //IDN置換
1699 private static readonly Uri SourceUriBase = new Uri("https://twitter.com/");
1702 /// Twitter APIから得たHTML形式のsource文字列を分析し、source名とURLに分離します
1704 public static Tuple<string, Uri> ParseSource(string sourceHtml)
1706 if (string.IsNullOrEmpty(sourceHtml))
1707 return Tuple.Create<string, Uri>("", null);
1712 // sourceHtmlの例: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
1714 var match = Regex.Match(sourceHtml, "^<a href=\"(?<uri>.+?)\".*?>(?<text>.+)</a>$", RegexOptions.IgnoreCase);
1717 sourceText = WebUtility.HtmlDecode(match.Groups["text"].Value);
1720 var uriStr = WebUtility.HtmlDecode(match.Groups["uri"].Value);
1721 sourceUri = new Uri(SourceUriBase, uriStr);
1723 catch (UriFormatException)
1730 sourceText = WebUtility.HtmlDecode(sourceHtml);
1734 return Tuple.Create(sourceText, sourceUri);
1737 public async Task<TwitterApiStatus> GetInfoApi()
1739 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid) return null;
1741 if (MyCommon._endingFlag) return null;
1743 var limits = await this.Api.ApplicationRateLimitStatus()
1744 .ConfigureAwait(false);
1746 MyCommon.TwitterApiInfo.UpdateFromJson(limits);
1748 return MyCommon.TwitterApiInfo;
1752 /// ブロック中のユーザーを更新します
1754 /// <exception cref="WebApiException"/>
1755 public async Task RefreshBlockIds()
1757 if (MyCommon._endingFlag) return;
1760 var newBlockIds = new HashSet<long>();
1763 var ret = await this.Api.BlocksIds(cursor)
1764 .ConfigureAwait(false);
1766 newBlockIds.UnionWith(ret.Ids);
1767 cursor = ret.NextCursor;
1768 } while (cursor != 0);
1770 newBlockIds.Remove(this.UserId); // 元のソースにあったので一応残しておく
1772 TabInformations.GetInstance().BlockIds = newBlockIds;
1776 /// ミュート中のユーザーIDを更新します
1778 /// <exception cref="WebApiException"/>
1779 public async Task RefreshMuteUserIdsAsync()
1781 if (MyCommon._endingFlag) return;
1783 var ids = await TwitterIds.GetAllItemsAsync(x => this.Api.MutesUsersIds(x))
1784 .ConfigureAwait(false);
1786 TabInformations.GetInstance().MuteUserIds = new HashSet<long>(ids);
1789 public string[] GetHashList()
1794 hashArray = _hashList.ToArray();
1800 public string AccessToken
1801 => ((TwitterApiConnection)this.Api.Connection).AccessToken;
1803 public string AccessTokenSecret
1804 => ((TwitterApiConnection)this.Api.Connection).AccessSecret;
1806 private void CheckAccountState()
1808 if (Twitter.AccountState != MyCommon.ACCOUNT_STATE.Valid)
1809 throw new WebApiException("Auth error. Check your account");
1812 private void CheckAccessLevel(TwitterApiAccessLevel accessLevelFlags)
1814 if (!this.AccessLevel.HasFlag(accessLevelFlags))
1815 throw new WebApiException("Auth Err:try to re-authorization.");
1818 private void CheckStatusCode(HttpStatusCode httpStatus, string responseText,
1819 [CallerMemberName] string callerMethodName = "")
1821 if (httpStatus == HttpStatusCode.OK)
1823 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
1827 if (string.IsNullOrWhiteSpace(responseText))
1829 if (httpStatus == HttpStatusCode.Unauthorized)
1830 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
1832 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")");
1837 var errors = TwitterError.ParseJson(responseText).Errors;
1838 if (errors == null || !errors.Any())
1840 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
1843 foreach (var error in errors)
1845 if (error.Code == TwitterErrorCode.InvalidToken ||
1846 error.Code == TwitterErrorCode.SuspendedAccount)
1848 Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
1852 throw new WebApiException("Err:" + string.Join(",", errors.Select(x => x.ToString())) + "(" + callerMethodName + ")", responseText);
1854 catch (SerializationException) { }
1856 throw new WebApiException("Err:" + httpStatus + "(" + callerMethodName + ")", responseText);
1859 public int GetTextLengthRemain(string postText)
1861 var matchDm = Twitter.DMSendTextRegex.Match(postText);
1862 if (matchDm.Success)
1863 return this.GetTextLengthRemainInternal(matchDm.Groups["body"].Value, isDm: true);
1865 return this.GetTextLengthRemainInternal(postText, isDm: false);
1868 private int GetTextLengthRemainInternal(string postText, bool isDm)
1873 while (pos < postText.Length)
1877 if (char.IsSurrogatePair(postText, pos))
1878 pos += 2; // サロゲートペアの場合は2文字分進める
1883 var urls = TweetExtractor.ExtractUrls(postText);
1884 foreach (var url in urls)
1886 var shortUrlLength = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
1887 ? this.Configuration.ShortUrlLengthHttps
1888 : this.Configuration.ShortUrlLength;
1890 textLength += shortUrlLength - url.Length;
1894 return this.Configuration.DmTextCharacterLimit - textLength;
1896 return 140 - textLength;
1900 #region "UserStream"
1901 private string trackWord_ = "";
1902 public string TrackWord
1913 private bool allAtReply_ = false;
1914 public bool AllAtReply
1922 allAtReply_ = value;
1926 public event EventHandler NewPostFromStream;
1927 public event EventHandler UserStreamStarted;
1928 public event EventHandler UserStreamStopped;
1929 public event EventHandler<PostDeletedEventArgs> PostDeleted;
1930 public event EventHandler<UserStreamEventReceivedEventArgs> UserStreamEventReceived;
1931 private DateTime _lastUserstreamDataReceived;
1932 private TwitterUserstream userStream;
1934 public class FormattedEvent
1936 public MyCommon.EVENTTYPE Eventtype { get; set; }
1937 public DateTime CreatedAt { get; set; }
1938 public string Event { get; set; }
1939 public string Username { get; set; }
1940 public string Target { get; set; }
1941 public Int64 Id { get; set; }
1942 public bool IsMe { get; set; }
1945 public List<FormattedEvent> storedEvent_ = new List<FormattedEvent>();
1946 public List<FormattedEvent> StoredEvent
1950 return storedEvent_;
1954 storedEvent_ = value;
1958 private readonly IReadOnlyDictionary<string, MyCommon.EVENTTYPE> eventTable = new Dictionary<string, MyCommon.EVENTTYPE>
1960 ["favorite"] = MyCommon.EVENTTYPE.Favorite,
1961 ["unfavorite"] = MyCommon.EVENTTYPE.Unfavorite,
1962 ["follow"] = MyCommon.EVENTTYPE.Follow,
1963 ["list_member_added"] = MyCommon.EVENTTYPE.ListMemberAdded,
1964 ["list_member_removed"] = MyCommon.EVENTTYPE.ListMemberRemoved,
1965 ["block"] = MyCommon.EVENTTYPE.Block,
1966 ["unblock"] = MyCommon.EVENTTYPE.Unblock,
1967 ["user_update"] = MyCommon.EVENTTYPE.UserUpdate,
1968 ["deleted"] = MyCommon.EVENTTYPE.Deleted,
1969 ["list_created"] = MyCommon.EVENTTYPE.ListCreated,
1970 ["list_destroyed"] = MyCommon.EVENTTYPE.ListDestroyed,
1971 ["list_updated"] = MyCommon.EVENTTYPE.ListUpdated,
1972 ["unfollow"] = MyCommon.EVENTTYPE.Unfollow,
1973 ["list_user_subscribed"] = MyCommon.EVENTTYPE.ListUserSubscribed,
1974 ["list_user_unsubscribed"] = MyCommon.EVENTTYPE.ListUserUnsubscribed,
1975 ["mute"] = MyCommon.EVENTTYPE.Mute,
1976 ["unmute"] = MyCommon.EVENTTYPE.Unmute,
1977 ["quoted_tweet"] = MyCommon.EVENTTYPE.QuotedTweet,
1980 public bool IsUserstreamDataReceived
1984 return DateTime.Now.Subtract(this._lastUserstreamDataReceived).TotalSeconds < 31;
1988 private void userStream_StatusArrived(string line)
1990 this._lastUserstreamDataReceived = DateTime.Now;
1991 if (string.IsNullOrEmpty(line)) return;
1993 if (line.First() != '{' || line.Last() != '}')
1995 MyCommon.TraceOut("Invalid JSON (StatusArrived):" + Environment.NewLine + line);
2003 using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(line), XmlDictionaryReaderQuotas.Max))
2005 var xElm = XElement.Load(jsonReader);
2006 if (xElm.Element("friends") != null)
2008 Debug.WriteLine("friends");
2011 else if (xElm.Element("delete") != null)
2013 Debug.WriteLine("delete");
2016 if ((idElm = xElm.Element("delete").Element("direct_message")?.Element("id")) != null)
2019 long.TryParse(idElm.Value, out id);
2021 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2023 else if ((idElm = xElm.Element("delete").Element("status")?.Element("id")) != null)
2026 long.TryParse(idElm.Value, out id);
2028 this.PostDeleted?.Invoke(this, new PostDeletedEventArgs(id));
2032 MyCommon.TraceOut("delete:" + line);
2035 for (int i = this.StoredEvent.Count - 1; i >= 0; i--)
2037 var sEvt = this.StoredEvent[i];
2038 if (sEvt.Id == id && (sEvt.Event == "favorite" || sEvt.Event == "unfavorite"))
2040 this.StoredEvent.RemoveAt(i);
2045 else if (xElm.Element("limit") != null)
2047 Debug.WriteLine(line);
2050 else if (xElm.Element("event") != null)
2052 Debug.WriteLine("event: " + xElm.Element("event").Value);
2053 CreateEventFromJson(line);
2056 else if (xElm.Element("direct_message") != null)
2058 Debug.WriteLine("direct_message");
2061 else if (xElm.Element("retweeted_status") != null)
2063 var sourceUserId = xElm.XPathSelectElement("/user/id_str").Value;
2064 var targetUserId = xElm.XPathSelectElement("/retweeted_status/user/id_str").Value;
2066 // 自分に関係しないリツイートの場合は無視する
2067 var selfUserId = this.UserId.ToString();
2068 if (sourceUserId == selfUserId || targetUserId == selfUserId)
2070 // 公式 RT をイベントとしても扱う
2071 var evt = CreateEventFromRetweet(xElm);
2074 this.StoredEvent.Insert(0, evt);
2076 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2080 // 従来通り公式 RT の表示も行うため return しない
2082 else if (xElm.Element("scrub_geo") != null)
2086 TabInformations.GetInstance().ScrubGeoReserve(long.Parse(xElm.Element("scrub_geo").Element("user_id").Value),
2087 long.Parse(xElm.Element("scrub_geo").Element("up_to_status_id").Value));
2091 MyCommon.TraceOut("scrub_geo:" + line);
2101 var message = TwitterStreamEventDirectMessage.ParseJson(line).DirectMessage;
2102 this.CreateDirectMessagesFromJson(new[] { message }, MyCommon.WORKERTYPE.UserStream, false);
2104 catch (SerializationException ex)
2106 throw TwitterApiException.CreateFromException(ex, line);
2113 var status = TwitterStatus.ParseJson(line);
2114 this.CreatePostsFromJson(new[] { status }, MyCommon.WORKERTYPE.UserStream, null, false);
2116 catch (SerializationException ex)
2118 throw TwitterApiException.CreateFromException(ex, line);
2122 catch (WebApiException ex)
2124 MyCommon.TraceOut(ex);
2127 catch(NullReferenceException)
2129 MyCommon.TraceOut("NullRef StatusArrived: " + line);
2132 this.NewPostFromStream?.Invoke(this, EventArgs.Empty);
2136 /// UserStreamsから受信した公式RTをイベントに変換します
2138 private FormattedEvent CreateEventFromRetweet(XElement xElm)
2140 return new FormattedEvent
2142 Eventtype = MyCommon.EVENTTYPE.Retweet,
2144 CreatedAt = MyCommon.DateTimeParse(xElm.XPathSelectElement("/created_at").Value),
2145 IsMe = xElm.XPathSelectElement("/user/id_str").Value == this.UserId.ToString(),
2146 Username = xElm.XPathSelectElement("/user/screen_name").Value,
2147 Target = string.Format("@{0}:{1}", new[]
2149 xElm.XPathSelectElement("/retweeted_status/user/screen_name").Value,
2150 WebUtility.HtmlDecode(xElm.XPathSelectElement("/retweeted_status/text").Value),
2152 Id = long.Parse(xElm.XPathSelectElement("/retweeted_status/id_str").Value),
2156 private void CreateEventFromJson(string content)
2158 TwitterStreamEvent eventData = null;
2161 eventData = TwitterStreamEvent.ParseJson(content);
2163 catch(SerializationException ex)
2165 MyCommon.TraceOut(ex, "Event Serialize Exception!" + Environment.NewLine + content);
2169 MyCommon.TraceOut(ex, "Event Exception!" + Environment.NewLine + content);
2172 var evt = new FormattedEvent();
2173 evt.CreatedAt = MyCommon.DateTimeParse(eventData.CreatedAt);
2174 evt.Event = eventData.Event;
2175 evt.Username = eventData.Source.ScreenName;
2176 evt.IsMe = evt.Username.ToLowerInvariant().Equals(this.Username.ToLowerInvariant());
2178 MyCommon.EVENTTYPE eventType;
2179 eventTable.TryGetValue(eventData.Event, out eventType);
2180 evt.Eventtype = eventType;
2182 TwitterStreamEvent<TwitterStatus> tweetEvent;
2184 switch (eventData.Event)
2186 case "access_revoked":
2187 case "access_unrevoked":
2189 case "user_suspend":
2192 if (eventData.Target.ScreenName.ToLowerInvariant().Equals(_uname))
2194 if (!this.followerId.Contains(eventData.Source.Id)) this.followerId.Add(eventData.Source.Id);
2198 return; //Block後のUndoをすると、SourceとTargetが逆転したfollowイベントが帰ってくるため。
2203 evt.Target = "@" + eventData.Target.ScreenName;
2205 case "favorited_retweet":
2206 case "retweeted_retweet":
2210 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2211 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2212 evt.Id = tweetEvent.TargetObject.Id;
2214 if (SettingCommon.Instance.IsRemoveSameEvent)
2216 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2220 var tabinfo = TabInformations.GetInstance();
2223 var statusId = tweetEvent.TargetObject.Id;
2224 if (!tabinfo.Posts.TryGetValue(statusId, out post))
2227 if (eventData.Event == "favorite")
2229 var favTab = tabinfo.GetTabByType(MyCommon.TabUsageType.Favorites);
2230 if (!favTab.Contains(post.StatusId))
2231 favTab.AddPostImmediately(post.StatusId, post.IsRead);
2233 if (tweetEvent.Source.Id == this.UserId)
2237 else if (tweetEvent.Target.Id == this.UserId)
2239 post.FavoritedCount++;
2241 if (SettingCommon.Instance.FavEventUnread)
2242 tabinfo.SetReadAllTab(post.StatusId, read: false);
2247 if (tweetEvent.Source.Id == this.UserId)
2251 else if (tweetEvent.Target.Id == this.UserId)
2253 post.FavoritedCount = Math.Max(0, post.FavoritedCount - 1);
2257 case "quoted_tweet":
2258 if (evt.IsMe) return;
2260 tweetEvent = TwitterStreamEvent<TwitterStatus>.ParseJson(content);
2261 evt.Target = "@" + tweetEvent.TargetObject.User.ScreenName + ":" + WebUtility.HtmlDecode(tweetEvent.TargetObject.Text);
2262 evt.Id = tweetEvent.TargetObject.Id;
2264 if (SettingCommon.Instance.IsRemoveSameEvent)
2266 if (this.StoredEvent.Any(ev => ev.Username == evt.Username && ev.Eventtype == evt.Eventtype && ev.Target == evt.Target))
2270 case "list_member_added":
2271 case "list_member_removed":
2272 case "list_created":
2273 case "list_destroyed":
2274 case "list_updated":
2275 case "list_user_subscribed":
2276 case "list_user_unsubscribed":
2277 var listEvent = TwitterStreamEvent<TwitterList>.ParseJson(content);
2278 evt.Target = listEvent.TargetObject.FullName;
2281 if (!TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Add(eventData.Target.Id);
2285 if (TabInformations.GetInstance().BlockIds.Contains(eventData.Target.Id)) TabInformations.GetInstance().BlockIds.Remove(eventData.Target.Id);
2294 evt.Target = "@" + eventData.Target.ScreenName;
2295 if (!TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2297 TabInformations.GetInstance().MuteUserIds.Add(eventData.Target.Id);
2301 evt.Target = "@" + eventData.Target.ScreenName;
2302 if (TabInformations.GetInstance().MuteUserIds.Contains(eventData.Target.Id))
2304 TabInformations.GetInstance().MuteUserIds.Remove(eventData.Target.Id);
2309 MyCommon.TraceOut("Unknown Event:" + evt.Event + Environment.NewLine + content);
2312 this.StoredEvent.Insert(0, evt);
2314 this.UserStreamEventReceived?.Invoke(this, new UserStreamEventReceivedEventArgs(evt));
2317 private void userStream_Started()
2319 this.UserStreamStarted?.Invoke(this, EventArgs.Empty);
2322 private void userStream_Stopped()
2324 this.UserStreamStopped?.Invoke(this, EventArgs.Empty);
2327 public bool UserStreamActive
2328 => this.userStream == null ? false : this.userStream.IsStreamActive;
2330 public void StartUserStream()
2332 var newStream = new TwitterUserstream(this.Api);
2334 newStream.StatusArrived += userStream_StatusArrived;
2335 newStream.Started += userStream_Started;
2336 newStream.Stopped += userStream_Stopped;
2338 newStream.Start(this.AllAtReply, this.TrackWord);
2340 var oldStream = Interlocked.Exchange(ref this.userStream, newStream);
2341 oldStream?.Dispose();
2344 public void StopUserStream()
2346 var oldStream = Interlocked.Exchange(ref this.userStream, null);
2347 oldStream?.Dispose();
2350 public void ReconnectUserStream()
2352 this.StartUserStream();
2355 private class TwitterUserstream : IDisposable
2357 public bool AllAtReplies { get; private set; }
2358 public string TrackWords { get; private set; }
2360 public bool IsStreamActive { get; private set; }
2362 public event Action<string> StatusArrived;
2363 public event Action Stopped;
2364 public event Action Started;
2366 private TwitterApi twitterApi;
2368 private Task streamTask;
2369 private CancellationTokenSource streamCts;
2371 public TwitterUserstream(TwitterApi twitterApi)
2373 this.twitterApi = twitterApi;
2376 public void Start(bool allAtReplies, string trackwords)
2378 this.AllAtReplies = allAtReplies;
2379 this.TrackWords = trackwords;
2381 var cts = new CancellationTokenSource();
2383 this.streamCts = cts;
2384 this.streamTask = Task.Run(async () =>
2388 await this.UserStreamLoop(cts.Token)
2389 .ConfigureAwait(false);
2391 catch (OperationCanceledException) { }
2397 this.streamCts?.Cancel();
2399 // streamTask の完了を待たずに IsStreamActive を false にセットする
2400 this.IsStreamActive = false;
2401 this.Stopped?.Invoke();
2404 private async Task UserStreamLoop(CancellationToken cancellationToken)
2406 TimeSpan? sleep = null;
2411 await Task.Delay(sleep.Value, cancellationToken)
2412 .ConfigureAwait(false);
2416 if (!MyCommon.IsNetworkAvailable())
2418 sleep = TimeSpan.FromSeconds(30);
2422 this.IsStreamActive = true;
2423 this.Started?.Invoke();
2427 var replies = this.AllAtReplies ? "all" : null;
2429 using (var stream = await this.twitterApi.UserStreams(replies, this.TrackWords)
2430 .ConfigureAwait(false))
2431 using (var reader = new StreamReader(stream))
2433 while (!reader.EndOfStream)
2435 var line = await reader.ReadLineAsync()
2436 .ConfigureAwait(false);
2438 cancellationToken.ThrowIfCancellationRequested();
2440 this.StatusArrived?.Invoke(line);
2444 // キャンセルされていないのにストリームが終了した場合
2445 sleep = TimeSpan.FromSeconds(30);
2447 catch (TwitterApiException) { sleep = TimeSpan.FromSeconds(30); }
2448 catch (IOException) { sleep = TimeSpan.FromSeconds(30); }
2449 catch (OperationCanceledException)
2451 if (cancellationToken.IsCancellationRequested)
2454 // cancellationToken によるキャンセルではない(=タイムアウトエラー)
2455 sleep = TimeSpan.FromSeconds(30);
2457 catch (Exception ex)
2459 MyCommon.ExceptionOut(ex);
2460 sleep = TimeSpan.FromSeconds(30);
2464 this.IsStreamActive = false;
2465 this.Stopped?.Invoke();
2470 private bool disposed = false;
2472 public void Dispose()
2477 this.disposed = true;
2481 this.Started = null;
2482 this.Stopped = null;
2483 this.StatusArrived = null;
2488 #region "IDisposable Support"
2489 private bool disposedValue; // 重複する呼び出しを検出するには
2492 protected virtual void Dispose(bool disposing)
2494 if (!this.disposedValue)
2498 this.StopUserStream();
2501 this.disposedValue = true;
2504 //protected Overrides void Finalize()
2506 // // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2508 // MyBase.Finalize()
2511 // このコードは、破棄可能なパターンを正しく実装できるように Visual Basic によって追加されました。
2512 public void Dispose()
2514 // このコードを変更しないでください。クリーンアップ コードを上の Dispose(bool disposing) に記述します。
2516 GC.SuppressFinalize(this);
2521 public class PostDeletedEventArgs : EventArgs
2523 public long StatusId { get; }
2525 public PostDeletedEventArgs(long statusId)
2527 this.StatusId = statusId;
2531 public class UserStreamEventReceivedEventArgs : EventArgs
2533 public Twitter.FormattedEvent EventData { get; }
2535 public UserStreamEventReceivedEventArgs(Twitter.FormattedEvent eventData)
2537 this.EventData = eventData;