From b82e830e8648bb0369e6857167037f16338ec833 Mon Sep 17 00:00:00 2001 From: Mark McDowall Date: Thu, 25 Jun 2015 00:10:40 -0700 Subject: [PATCH] Cleanup and refactoring of Twitter notifications Closes #301 New: Twitter Notifications --- .../Frontend/Mappers/StaticResourceMapper.cs | 3 +- .../Annotations/FieldDefinitionAttribute.cs | 3 +- .../Notifications/Twitter/Twitter.cs | 50 +- .../Notifications/Twitter/TwitterException.cs | 24 + .../Notifications/Twitter/TwitterService.cs | 127 +++-- .../Notifications/Twitter/TwitterSettings.cs | 36 +- src/NzbDrone.Core/NzbDrone.Core.csproj | 1 + src/NzbDrone.Core/TinyTwitter.cs | 519 +++++++++--------- src/UI/Form/ActionTemplate.hbs | 2 +- .../Edit/NotificationEditView.js | 25 +- .../Edit/NotificationEditViewTemplate.hbs | 2 +- src/UI/Settings/ProviderSettingsModelBase.js | 69 ++- src/UI/{Content/oauthLand.html => oauth.html} | 0 13 files changed, 474 insertions(+), 387 deletions(-) create mode 100644 src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs rename src/UI/{Content/oauthLand.html => oauth.html} (100%) diff --git a/src/NzbDrone.Api/Frontend/Mappers/StaticResourceMapper.cs b/src/NzbDrone.Api/Frontend/Mappers/StaticResourceMapper.cs index f22ff9ce1..61ed14e9b 100644 --- a/src/NzbDrone.Api/Frontend/Mappers/StaticResourceMapper.cs +++ b/src/NzbDrone.Api/Frontend/Mappers/StaticResourceMapper.cs @@ -33,7 +33,8 @@ namespace NzbDrone.Api.Frontend.Mappers resourceUrl.EndsWith(".map") || resourceUrl.EndsWith(".css") || (resourceUrl.EndsWith(".ico") && !resourceUrl.Equals("/favicon.ico")) || - resourceUrl.EndsWith(".swf"); + resourceUrl.EndsWith(".swf") || + resourceUrl.EndsWith("oauth.html"); } } } \ No newline at end of file diff --git a/src/NzbDrone.Core/Annotations/FieldDefinitionAttribute.cs b/src/NzbDrone.Core/Annotations/FieldDefinitionAttribute.cs index 53e79d31a..2d6dc5249 100644 --- a/src/NzbDrone.Core/Annotations/FieldDefinitionAttribute.cs +++ b/src/NzbDrone.Core/Annotations/FieldDefinitionAttribute.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; namespace NzbDrone.Core.Annotations { @@ -28,7 +27,7 @@ namespace NzbDrone.Core.Annotations Select, Path, Hidden, - Tag + Tag, Action } } \ No newline at end of file diff --git a/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs b/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs index fe81ad80b..a6ef406c6 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs @@ -2,21 +2,17 @@ using FluentValidation.Results; using NzbDrone.Common.Extensions; using NzbDrone.Core.Tv; -using System; -using OAuth; -using System.Net; -using System.IO; namespace NzbDrone.Core.Notifications.Twitter { class Twitter : NotificationBase { - private readonly ITwitterService _TwitterService; + private readonly ITwitterService _twitterService; - public Twitter(ITwitterService TwitterService) + public Twitter(ITwitterService twitterService) { - _TwitterService = TwitterService; + _twitterService = twitterService; } public override string Link @@ -26,15 +22,15 @@ namespace NzbDrone.Core.Notifications.Twitter public override void OnGrab(string message) { - _TwitterService.SendNotification(message, Settings.AccessToken, Settings.AccessTokenSecret, Settings.ConsumerKey, Settings.ConsumerSecret); + _twitterService.SendNotification(message, Settings); } public override void OnDownload(DownloadMessage message) { - _TwitterService.SendNotification(message.Message, Settings.AccessToken, Settings.AccessTokenSecret, Settings.ConsumerKey, Settings.ConsumerSecret); + _twitterService.SendNotification(message.Message, Settings); } - public override void AfterRename(Series series) + public override void OnRename(Series series) { } @@ -45,34 +41,42 @@ namespace NzbDrone.Core.Notifications.Twitter return new { nextStep = "step2", - action = "openwindow", - url = _TwitterService.GetOAuthRedirect( - Settings.ConsumerKey, - Settings.ConsumerSecret, - "http://localhost:8989/Content/oauthLand.html" /* FIXME - how do I get http host and such */ - ) + action = "openWindow", + url = _twitterService.GetOAuthRedirect(query["callbackUrl"].ToString()) }; } else if (stage == "step2") { return new { - action = "updatefields", - fields = _TwitterService.GetOAuthToken( - Settings.ConsumerKey, Settings.ConsumerSecret, - query["oauth_token"].ToString(), - query["oauth_verifier"].ToString() - ) + action = "updateFields", + fields = _twitterService.GetOAuthToken(query["oauth_token"].ToString(), query["oauth_verifier"].ToString()) }; } return new {}; } + public override string Name + { + get + { + return "Twitter"; + } + } + + public override bool SupportsOnRename + { + get + { + return false; + } + } + public override ValidationResult Test() { var failures = new List(); - failures.AddIfNotNull(_TwitterService.Test(Settings)); + failures.AddIfNotNull(_twitterService.Test(Settings)); return new ValidationResult(failures); } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs new file mode 100644 index 000000000..99146fa71 --- /dev/null +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs @@ -0,0 +1,24 @@ +using System; +using NzbDrone.Common.Exceptions; + +namespace NzbDrone.Core.Notifications.Twitter +{ + public class TwitterException : NzbDroneException + { + public TwitterException(string message, params object[] args) : base(message, args) + { + } + + public TwitterException(string message) : base(message) + { + } + + public TwitterException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + { + } + + public TwitterException(string message, Exception innerException) : base(message, innerException) + { + } + } +} diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs index fadfa29d7..3675b9da2 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs @@ -1,64 +1,54 @@ using FluentValidation.Results; -using NzbDrone.Common.Extensions; using NLog; using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; using OAuth; using System.Net; using System.Collections.Specialized; +using System.IO; +using System.Web; +using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; namespace NzbDrone.Core.Notifications.Twitter { public interface ITwitterService { - void SendNotification(string message, String accessToken, String accessTokenSecret, String consumerKey, String consumerSecret); + void SendNotification(string message, TwitterSettings settings); ValidationFailure Test(TwitterSettings settings); - string GetOAuthRedirect(string consumerKey, string consumerSecret, string callback); - object GetOAuthToken(string consumerKey, string consumerSecret, string oauthToken, string oauthVerifier); + string GetOAuthRedirect(string callbackUrl); + object GetOAuthToken(string oauthToken, string oauthVerifier); } public class TwitterService : ITwitterService { + private readonly IHttpClient _httpClient; private readonly Logger _logger; - public TwitterService(Logger logger) + private static string _consumerKey = "5jSR8a3cp0ToOqSMLMv5GtMQD"; + private static string _consumerSecret = "dxoZjyMq4BLsC8KxyhSOrIndhCzJ0Dik2hrLzqyJcqoGk4Pfsp"; + + public TwitterService(IHttpClient httpClient, Logger logger) { + _httpClient = httpClient; _logger = logger; - - var logo = typeof(TwitterService).Assembly.GetManifestResourceBytes("NzbDrone.Core.Resources.Logo.64.png"); } - private NameValueCollection oauthQuery(OAuthRequest client) + private NameValueCollection OAuthQuery(OAuthRequest oAuthRequest) { - // Using HTTP header authorization - string auth = client.GetAuthorizationHeader(); - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(client.RequestUrl); - + var auth = oAuthRequest.GetAuthorizationHeader(); + var request = new Common.Http.HttpRequest(oAuthRequest.RequestUrl); request.Headers.Add("Authorization", auth); - HttpWebResponse response = (HttpWebResponse)request.GetResponse(); - System.Collections.Specialized.NameValueCollection qscoll; - using (var reader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))) - { - string responseText = reader.ReadToEnd(); - return System.Web.HttpUtility.ParseQueryString(responseText); - } - return null; + var response = _httpClient.Get(request); + + return HttpUtility.ParseQueryString(response.Content); } - public object GetOAuthToken(string consumerKey, string consumerSecret, string oauthToken, string oauthVerifier) + public object GetOAuthToken(string oauthToken, string oauthVerifier) { // Creating a new instance with a helper method - OAuthRequest client = OAuthRequest.ForAccessToken( - consumerKey, - consumerSecret, - oauthToken, - "", - oauthVerifier - ); - client.RequestUrl = "https://api.twitter.com/oauth/access_token"; - NameValueCollection qscoll = oauthQuery(client); + var oAuthRequest = OAuthRequest.ForAccessToken(_consumerKey, _consumerSecret, oauthToken, "", oauthVerifier); + oAuthRequest.RequestUrl = "https://api.twitter.com/oauth/access_token"; + var qscoll = OAuthQuery(oAuthRequest); return new { @@ -67,54 +57,77 @@ namespace NzbDrone.Core.Notifications.Twitter }; } - public string GetOAuthRedirect(string consumerKey, string consumerSecret, string callback) + public string GetOAuthRedirect(string callbackUrl) { // Creating a new instance with a helper method - OAuthRequest client = OAuthRequest.ForRequestToken(consumerKey, consumerSecret, callback); - client.RequestUrl = "https://api.twitter.com/oauth/request_token"; - NameValueCollection qscoll = oauthQuery(client); + var oAuthRequest = OAuthRequest.ForRequestToken(_consumerKey, _consumerSecret, callbackUrl); + oAuthRequest.RequestUrl = "https://api.twitter.com/oauth/request_token"; + var qscoll = OAuthQuery(oAuthRequest); - return "https://api.twitter.com/oauth/authorize?oauth_token=" + qscoll["oauth_token"]; + return String.Format("https://api.twitter.com/oauth/authorize?oauth_token={0}", qscoll["oauth_token"]); } - public void SendNotification(string message, String accessToken, String accessTokenSecret, String consumerKey, String consumerSecret) + public void SendNotification(string message, TwitterSettings settings) { try { - var oauth = new TinyTwitter.OAuthInfo + var oAuth = new TinyTwitter.OAuthInfo { - AccessToken = accessToken, - AccessSecret = accessTokenSecret, - ConsumerKey = consumerKey, - ConsumerSecret = consumerSecret + AccessToken = settings.AccessToken, + AccessSecret = settings.AccessTokenSecret, + ConsumerKey = _consumerKey, + ConsumerSecret = _consumerSecret }; - var twitter = new TinyTwitter.TinyTwitter(oauth); - twitter.UpdateStatus(message); + + var twitter = new TinyTwitter.TinyTwitter(oAuth); + + if (settings.DirectMessage) + { + twitter.DirectMessage(message, settings.Mention); + } + + else + { + if (settings.Mention.IsNotNullOrWhiteSpace()) + { + message += String.Format(" @{0}", settings.Mention); + } + + twitter.UpdateStatus(message); + } } catch (WebException e) { - using (WebResponse response = e.Response) + using (var response = e.Response) { - HttpWebResponse httpResponse = (HttpWebResponse)response; - Console.WriteLine("Error code: {0}", httpResponse.StatusCode); - using (System.IO.Stream data = response.GetResponseStream()) - using (var reader = new System.IO.StreamReader(data)) + var httpResponse = (HttpWebResponse)response; + + using (var responseStream = response.GetResponseStream()) { - string text = reader.ReadToEnd(); - Console.WriteLine(text); + if (responseStream == null) + { + _logger.Trace("Status Code: {0}", httpResponse.StatusCode); + throw new TwitterException("Error received from Twitter: " + httpResponse.StatusCode, _logger , e); + } + + using (var reader = new StreamReader(responseStream)) + { + var responseBody = reader.ReadToEnd(); + _logger.Trace("Reponse: {0} Status Code: {1}", responseBody, httpResponse.StatusCode); + throw new TwitterException("Error received from Twitter: " + responseBody, _logger, e); + } } } - throw e; } - return; } public ValidationFailure Test(TwitterSettings settings) { try { - string body = "This is a test message from Sonarr @ " + DateTime.Now.ToString(); - SendNotification(body, settings.AccessToken, settings.AccessTokenSecret, settings.ConsumerKey, settings.ConsumerSecret); + var body = "Sonarr: Test Message @ " + DateTime.Now; + + SendNotification(body, settings); } catch (Exception ex) { diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs index 27b086fcd..2be9cb409 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs @@ -1,5 +1,4 @@ -using System; -using FluentValidation; +using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; @@ -12,8 +11,12 @@ namespace NzbDrone.Core.Notifications.Twitter { RuleFor(c => c.AccessToken).NotEmpty(); RuleFor(c => c.AccessTokenSecret).NotEmpty(); - RuleFor(c => c.ConsumerKey).NotEmpty(); - RuleFor(c => c.ConsumerSecret).NotEmpty(); + //TODO: Validate that it is a valid username (numbers, letters and underscores - I think) + RuleFor(c => c.Mention).NotEmpty().When(c => c.DirectMessage); + + RuleFor(c => c.DirectMessage).Equal(true) + .WithMessage("Using Direct Messaging is recommended, or use a private account.") + .AsWarning(); } } @@ -23,31 +26,24 @@ namespace NzbDrone.Core.Notifications.Twitter public TwitterSettings() { - ConsumerKey = "3POVsO3KW90LKZXyzPOjQ"; /* FIXME - Key from Couchpotato so needs to be replaced */ - ConsumerSecret = "Qprb94hx9ucXvD4Wvg2Ctsk4PDK7CcQAKgCELXoyIjE"; /* FIXME - Key from Couchpotato so needs to be replaced */ + DirectMessage = true; AuthorizeNotification = "step1"; } [FieldDefinition(0, Label = "Access Token", Advanced = true)] - public String AccessToken { get; set; } + public string AccessToken { get; set; } [FieldDefinition(1, Label = "Access Token Secret", Advanced = true)] - public String AccessTokenSecret { get; set; } + public string AccessTokenSecret { get; set; } - public String ConsumerKey { get; set; } - public String ConsumerSecret { get; set; } + [FieldDefinition(2, Label = "Mention", HelpText = "Mention this user in sent tweets")] + public string Mention { get; set; } - [FieldDefinition(4, Label = "Connect to twitter", Type = FieldType.Action)] - public String AuthorizeNotification { get; set; } + [FieldDefinition(3, Label = "Direct Message", Type = FieldType.Checkbox, HelpText = "Send a direct message instead of a public message")] + public bool DirectMessage { get; set; } - public bool IsValid - { - get - { - return !string.IsNullOrWhiteSpace(AccessToken) && !string.IsNullOrWhiteSpace(AccessTokenSecret) && - !string.IsNullOrWhiteSpace(ConsumerKey) && !string.IsNullOrWhiteSpace(ConsumerSecret); - } - } + [FieldDefinition(4, Label = "Connect to twitter", Type = FieldType.Action)] + public string AuthorizeNotification { get; set; } public NzbDroneValidationResult Validate() { diff --git a/src/NzbDrone.Core/NzbDrone.Core.csproj b/src/NzbDrone.Core/NzbDrone.Core.csproj index ba494028b..f10c85961 100644 --- a/src/NzbDrone.Core/NzbDrone.Core.csproj +++ b/src/NzbDrone.Core/NzbDrone.Core.csproj @@ -743,6 +743,7 @@ + diff --git a/src/NzbDrone.Core/TinyTwitter.cs b/src/NzbDrone.Core/TinyTwitter.cs index 7c05dd65e..508783b6b 100644 --- a/src/NzbDrone.Core/TinyTwitter.cs +++ b/src/NzbDrone.Core/TinyTwitter.cs @@ -11,252 +11,281 @@ using System.Web.Script.Serialization; namespace TinyTwitter { - public class OAuthInfo - { - public string ConsumerKey { get; set; } - public string ConsumerSecret { get; set; } - public string AccessToken { get; set; } - public string AccessSecret { get; set; } - } - - public class Tweet - { - public long Id { get; set; } - public DateTime CreatedAt { get; set; } - public string UserName { get; set; } - public string ScreenName { get; set; } - public string Text { get; set; } - } - - public class TinyTwitter - { - private readonly OAuthInfo oauth; - - public TinyTwitter(OAuthInfo oauth) - { - this.oauth = oauth; - } - - public void UpdateStatus(string message) - { - new RequestBuilder(oauth, "POST", "https://api.twitter.com/1.1/statuses/update.json") - .AddParameter("status", message) - .Execute(); - } - - public IEnumerable GetHomeTimeline(long? sinceId = null, int? count = 20) - { - return GetTimeline("http://api.twitter.com/1.1/statuses/home_timeline.json", sinceId, count); - } - - public IEnumerable GetMentions(long? sinceId = null, int? count = 20) - { - return GetTimeline("http://api.twitter.com/1.1/statuses/mentions.json", sinceId, count); - } - - public IEnumerable GetUserTimeline(long? sinceId = null, int? count = 20) - { - return GetTimeline("http://api.twitter.com/1.1/statuses/user_timeline.json", sinceId, count); - } - - private IEnumerable GetTimeline(string url, long? sinceId, int? count) - { - var builder = new RequestBuilder(oauth, "GET", url); - - if (sinceId.HasValue) - builder.AddParameter("since_id", sinceId.Value.ToString()); - - if (count.HasValue) - builder.AddParameter("count", count.Value.ToString()); - - using (var response = builder.Execute()) - using (var stream = response.GetResponseStream()) - using (var reader = new StreamReader(stream)) - { - var content = reader.ReadToEnd(); - var serializer = new JavaScriptSerializer(); - - var tweets = (object[])serializer.DeserializeObject(content); - - return tweets.Cast>().Select(tweet => - { - var user = ((Dictionary)tweet["user"]); - var date = DateTime.ParseExact(tweet["created_at"].ToString(), - "ddd MMM dd HH:mm:ss zz00 yyyy", - CultureInfo.InvariantCulture).ToLocalTime(); - return new Tweet - { - Id = (long)tweet["id"], - CreatedAt = - date, - Text = (string)tweet["text"], - UserName = (string)user["name"], - ScreenName = (string)user["screen_name"] - }; - }).ToArray(); - } - } - - #region RequestBuilder - - public class RequestBuilder - { - private const string VERSION = "1.0"; - private const string SIGNATURE_METHOD = "HMAC-SHA1"; - - private readonly OAuthInfo oauth; - private readonly string method; - private readonly IDictionary customParameters; - private readonly string url; - - public RequestBuilder(OAuthInfo oauth, string method, string url) - { - this.oauth = oauth; - this.method = method; - this.url = url; - customParameters = new Dictionary(); - } - - public RequestBuilder AddParameter(string name, string value) - { - customParameters.Add(name, value.EncodeRFC3986()); - return this; - } - - public WebResponse Execute() - { - var timespan = GetTimestamp(); - var nonce = CreateNonce(); - - var parameters = new Dictionary(customParameters); - AddOAuthParameters(parameters, timespan, nonce); - - var signature = GenerateSignature(parameters); - var headerValue = GenerateAuthorizationHeaderValue(parameters, signature); - - var request = (HttpWebRequest)WebRequest.Create(GetRequestUrl()); - request.Method = method; - request.ContentType = "application/x-www-form-urlencoded"; - - request.Headers.Add("Authorization", headerValue); - - WriteRequestBody(request); - - // It looks like a bug in HttpWebRequest. It throws random TimeoutExceptions - // after some requests. Abort the request seems to work. More info: - // http://stackoverflow.com/questions/2252762/getrequeststream-throws-timeout-exception-randomly + public class OAuthInfo + { + public string ConsumerKey { get; set; } + public string ConsumerSecret { get; set; } + public string AccessToken { get; set; } + public string AccessSecret { get; set; } + } + + public class Tweet + { + public long Id { get; set; } + public DateTime CreatedAt { get; set; } + public string UserName { get; set; } + public string ScreenName { get; set; } + public string Text { get; set; } + } + + public class TinyTwitter + { + private readonly OAuthInfo oauth; + + public TinyTwitter(OAuthInfo oauth) + { + this.oauth = oauth; + } + + public void UpdateStatus(string message) + { + new RequestBuilder(oauth, "POST", "https://api.twitter.com/1.1/statuses/update.json") + .AddParameter("status", message) + .Execute(); + } + + /** + * + * As of June 26th 2015 Direct Messaging is not part of TinyTwitter. + * I have added it to Sonarr's copy to make our implementation easier + * and added this banner so it's not blindly updated. + * + **/ + + public void DirectMessage(string message, string screenName) + { + new RequestBuilder(oauth, "POST", "https://api.twitter.com/1.1/direct_messages/new.json") + .AddParameter("text", message) + .AddParameter("screen_name", screenName) + .Execute(); + } + + public IEnumerable GetHomeTimeline(long? sinceId = null, long? maxId = null, int? count = 20) + { + return GetTimeline("https://api.twitter.com/1.1/statuses/home_timeline.json", sinceId, maxId, count, ""); + } + + public IEnumerable GetMentions(long? sinceId = null, long? maxId = null, int? count = 20) + { + return GetTimeline("https://api.twitter.com/1.1/statuses/mentions.json", sinceId, maxId, count, ""); + } + + public IEnumerable GetUserTimeline(long? sinceId = null, long? maxId = null, int? count = 20, string screenName = "") + { + return GetTimeline("https://api.twitter.com/1.1/statuses/user_timeline.json", sinceId, maxId, count, screenName); + } + + private IEnumerable GetTimeline(string url, long? sinceId, long? maxId, int? count, string screenName) + { + var builder = new RequestBuilder(oauth, "GET", url); + + if (sinceId.HasValue) + builder.AddParameter("since_id", sinceId.Value.ToString()); + + if (maxId.HasValue) + builder.AddParameter("max_id", maxId.Value.ToString()); + + if (count.HasValue) + builder.AddParameter("count", count.Value.ToString()); + + if (screenName != "") + builder.AddParameter("screen_name", screenName); + + var responseContent = builder.Execute(); + + var serializer = new JavaScriptSerializer(); + + var tweets = (object[])serializer.DeserializeObject(responseContent); + + return tweets.Cast>().Select(tweet => + { + var user = ((Dictionary)tweet["user"]); + var date = DateTime.ParseExact(tweet["created_at"].ToString(), + "ddd MMM dd HH:mm:ss zz00 yyyy", + CultureInfo.InvariantCulture).ToLocalTime(); + + return new Tweet + { + Id = (long)tweet["id"], + CreatedAt = date, + Text = (string)tweet["text"], + UserName = (string)user["name"], + ScreenName = (string)user["screen_name"] + }; + }).ToArray(); + } + + #region RequestBuilder + + public class RequestBuilder + { + private const string VERSION = "1.0"; + private const string SIGNATURE_METHOD = "HMAC-SHA1"; + + private readonly OAuthInfo oauth; + private readonly string method; + private readonly IDictionary customParameters; + private readonly string url; + + public RequestBuilder(OAuthInfo oauth, string method, string url) + { + this.oauth = oauth; + this.method = method; + this.url = url; + customParameters = new Dictionary(); + } + + public RequestBuilder AddParameter(string name, string value) + { + customParameters.Add(name, value.EncodeRFC3986()); + return this; + } + + public string Execute() + { + var timespan = GetTimestamp(); + var nonce = CreateNonce(); + + var parameters = new Dictionary(customParameters); + AddOAuthParameters(parameters, timespan, nonce); + + var signature = GenerateSignature(parameters); + var headerValue = GenerateAuthorizationHeaderValue(parameters, signature); + + var request = (HttpWebRequest)WebRequest.Create(GetRequestUrl()); + request.Method = method; + request.ContentType = "application/x-www-form-urlencoded"; + + request.Headers.Add("Authorization", headerValue); + + WriteRequestBody(request); + + // It looks like a bug in HttpWebRequest. It throws random TimeoutExceptions + // after some requests. Abort the request seems to work. More info: + // http://stackoverflow.com/questions/2252762/getrequeststream-throws-timeout-exception-randomly var response = request.GetResponse(); + + string content; + + using (var stream = response.GetResponseStream()) + { + using (var reader = new StreamReader(stream)) + { + content = reader.ReadToEnd(); + } + } + request.Abort(); - return response; - } - - private void WriteRequestBody(HttpWebRequest request) - { - if (method == "GET") - return; - - var requestBody = Encoding.ASCII.GetBytes(GetCustomParametersString()); - using (var stream = request.GetRequestStream()) - stream.Write(requestBody, 0, requestBody.Length); - } - - private string GetRequestUrl() - { - if (method != "GET" || customParameters.Count == 0) - return url; - - return string.Format("{0}?{1}", url, GetCustomParametersString()); - } - - private string GetCustomParametersString() - { - return customParameters.Select(x => string.Format("{0}={1}", x.Key, x.Value)).Join("&"); - } - - private string GenerateAuthorizationHeaderValue(IEnumerable> parameters, string signature) - { - return new StringBuilder("OAuth ") - .Append(parameters.Concat(new KeyValuePair("oauth_signature", signature)) - .Where(x => x.Key.StartsWith("oauth_")) - .Select(x => string.Format("{0}=\"{1}\"", x.Key, x.Value.EncodeRFC3986())) - .Join(",")) - .ToString(); - } - - private string GenerateSignature(IEnumerable> parameters) - { - var dataToSign = new StringBuilder() - .Append(method).Append("&") - .Append(url.EncodeRFC3986()).Append("&") - .Append(parameters - .OrderBy(x => x.Key) - .Select(x => string.Format("{0}={1}", x.Key, x.Value)) - .Join("&") - .EncodeRFC3986()); - - var signatureKey = string.Format("{0}&{1}", oauth.ConsumerSecret.EncodeRFC3986(), oauth.AccessSecret.EncodeRFC3986()); - var sha1 = new HMACSHA1(Encoding.ASCII.GetBytes(signatureKey)); - - var signatureBytes = sha1.ComputeHash(Encoding.ASCII.GetBytes(dataToSign.ToString())); - return Convert.ToBase64String(signatureBytes); - } - - private void AddOAuthParameters(IDictionary parameters, string timestamp, string nonce) - { - parameters.Add("oauth_version", VERSION); - parameters.Add("oauth_consumer_key", oauth.ConsumerKey); - parameters.Add("oauth_nonce", nonce); - parameters.Add("oauth_signature_method", SIGNATURE_METHOD); - parameters.Add("oauth_timestamp", timestamp); - parameters.Add("oauth_token", oauth.AccessToken); - } - - private static string GetTimestamp() - { - return ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString(); - } - - private static string CreateNonce() - { - return new Random().Next(0x0000000, 0x7fffffff).ToString("X8"); - } - } - - #endregion - } - - public static class TinyTwitterHelperExtensions - { - public static string Join(this IEnumerable items, string separator) - { - return string.Join(separator, items.ToArray()); - } - - public static IEnumerable Concat(this IEnumerable items, T value) - { - return items.Concat(new[] { value }); - } - - public static string EncodeRFC3986(this string value) - { - // From Twitterizer http://www.twitterizer.net/ - - if (string.IsNullOrEmpty(value)) - return string.Empty; - - var encoded = Uri.EscapeDataString(value); - - return Regex - .Replace(encoded, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper()) - .Replace("(", "%28") - .Replace(")", "%29") - .Replace("$", "%24") - .Replace("!", "%21") - .Replace("*", "%2A") - .Replace("'", "%27") - .Replace("%7E", "~"); - } - } -} + return content; + } + + private void WriteRequestBody(HttpWebRequest request) + { + if (method == "GET") + return; + + var requestBody = Encoding.ASCII.GetBytes(GetCustomParametersString()); + using (var stream = request.GetRequestStream()) + stream.Write(requestBody, 0, requestBody.Length); + } + + private string GetRequestUrl() + { + if (method != "GET" || customParameters.Count == 0) + return url; + + return string.Format("{0}?{1}", url, GetCustomParametersString()); + } + + private string GetCustomParametersString() + { + return customParameters.Select(x => string.Format("{0}={1}", x.Key, x.Value)).Join("&"); + } + + private string GenerateAuthorizationHeaderValue(IEnumerable> parameters, string signature) + { + return new StringBuilder("OAuth ") + .Append(parameters.Concat(new KeyValuePair("oauth_signature", signature)) + .Where(x => x.Key.StartsWith("oauth_")) + .Select(x => string.Format("{0}=\"{1}\"", x.Key, x.Value.EncodeRFC3986())) + .Join(",")) + .ToString(); + } + + private string GenerateSignature(IEnumerable> parameters) + { + var dataToSign = new StringBuilder() + .Append(method).Append("&") + .Append(url.EncodeRFC3986()).Append("&") + .Append(parameters + .OrderBy(x => x.Key) + .Select(x => string.Format("{0}={1}", x.Key, x.Value)) + .Join("&") + .EncodeRFC3986()); + + var signatureKey = string.Format("{0}&{1}", oauth.ConsumerSecret.EncodeRFC3986(), oauth.AccessSecret.EncodeRFC3986()); + var sha1 = new HMACSHA1(Encoding.ASCII.GetBytes(signatureKey)); + + var signatureBytes = sha1.ComputeHash(Encoding.ASCII.GetBytes(dataToSign.ToString())); + return Convert.ToBase64String(signatureBytes); + } + + private void AddOAuthParameters(IDictionary parameters, string timestamp, string nonce) + { + parameters.Add("oauth_version", VERSION); + parameters.Add("oauth_consumer_key", oauth.ConsumerKey); + parameters.Add("oauth_nonce", nonce); + parameters.Add("oauth_signature_method", SIGNATURE_METHOD); + parameters.Add("oauth_timestamp", timestamp); + parameters.Add("oauth_token", oauth.AccessToken); + } + + private static string GetTimestamp() + { + return ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString(); + } + + private static string CreateNonce() + { + return new Random().Next(0x0000000, 0x7fffffff).ToString("X8"); + } + } + + #endregion + } + + public static class TinyTwitterHelperExtensions + { + public static string Join(this IEnumerable items, string separator) + { + return string.Join(separator, items.ToArray()); + } + + public static IEnumerable Concat(this IEnumerable items, T value) + { + return items.Concat(new[] { value }); + } + + public static string EncodeRFC3986(this string value) + { + // From Twitterizer http://www.twitterizer.net/ + + if (string.IsNullOrEmpty(value)) + return string.Empty; + + var encoded = Uri.EscapeDataString(value); + + return Regex + .Replace(encoded, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper()) + .Replace("(", "%28") + .Replace(")", "%29") + .Replace("$", "%24") + .Replace("!", "%21") + .Replace("*", "%2A") + .Replace("'", "%27") + .Replace("%7E", "~"); + } + } +} \ No newline at end of file diff --git a/src/UI/Form/ActionTemplate.hbs b/src/UI/Form/ActionTemplate.hbs index 73991a2da..27ffcb538 100644 --- a/src/UI/Form/ActionTemplate.hbs +++ b/src/UI/Form/ActionTemplate.hbs @@ -2,6 +2,6 @@
- +
diff --git a/src/UI/Settings/Notifications/Edit/NotificationEditView.js b/src/UI/Settings/Notifications/Edit/NotificationEditView.js index 839d9311c..e6ad3231a 100644 --- a/src/UI/Settings/Notifications/Edit/NotificationEditView.js +++ b/src/UI/Settings/Notifications/Edit/NotificationEditView.js @@ -16,12 +16,10 @@ var view = Marionette.ItemView.extend({ onDownloadToggle : '.x-on-download', onUpgradeSection : '.x-on-upgrade', tags : '.x-tags', - indicator : '.x-indicator', + modalBody : '.x-modal-body', + formTag : '.x-form-tag', + path : '.x-path', authorizedNotificationButton : '.AuthorizeNotification' - tags : '.x-tags', - modalBody : '.modal-body', - formTag : '.x-form-tag', - path : '.x-path' }, events : { @@ -87,13 +85,16 @@ var view = Marionette.ItemView.extend({ } }, - _onAuthorizeNotification : function(e) { - var self = this; - self.ui.indicator.show(); - this.model.connectData(this.ui.authorizedNotificationButton.data('value')).always(function(newValues) { - self.ui.indicator.hide(); - }); - } + _onAuthorizeNotification : function() { + var self = this; + var callbackUrl = window.location.origin + '/oauth.html'; + this.ui.indicator.show(); + var promise = this.model.connectData(this.ui.authorizedNotificationButton.data('value') + '?callbackUrl=' + callbackUrl); + + promise.always(function() { + self.ui.indicator.hide(); + }); + } }); AsModelBoundView.call(view); diff --git a/src/UI/Settings/Notifications/Edit/NotificationEditViewTemplate.hbs b/src/UI/Settings/Notifications/Edit/NotificationEditViewTemplate.hbs index 8833326e9..02196cb75 100644 --- a/src/UI/Settings/Notifications/Edit/NotificationEditViewTemplate.hbs +++ b/src/UI/Settings/Notifications/Edit/NotificationEditViewTemplate.hbs @@ -7,7 +7,7 @@

Add - {{implementationName}}

{{/if}} -