Cleanup and refactoring of Twitter notifications

Closes #301
New: Twitter Notifications
pull/644/head
Mark McDowall 9 years ago
parent 2fbf7a4114
commit b82e830e86

@ -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");
}
}
}

@ -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
}
}

@ -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<TwitterSettings>
{
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<ValidationFailure>();
failures.AddIfNotNull(_TwitterService.Test(Settings));
failures.AddIfNotNull(_twitterService.Test(Settings));
return new ValidationResult(failures);
}

@ -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)
{
}
}
}

@ -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);
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)
{

@ -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()
{

@ -743,6 +743,7 @@
<Compile Include="Notifications\Synology\SynologyIndexer.cs" />
<Compile Include="Notifications\Synology\SynologyIndexerProxy.cs" />
<Compile Include="Notifications\Synology\SynologyIndexerSettings.cs" />
<Compile Include="Notifications\Twitter\TwitterException.cs" />
<Compile Include="Organizer\NamingConfigRepository.cs" />
<Compile Include="Notifications\Twitter\Twitter.cs" />
<Compile Include="Notifications\Twitter\TwitterService.cs" />

@ -44,39 +44,58 @@ namespace TinyTwitter
.Execute();
}
public IEnumerable<Tweet> GetHomeTimeline(long? sinceId = null, int? count = 20)
/**
*
* 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)
{
return GetTimeline("http://api.twitter.com/1.1/statuses/home_timeline.json", sinceId, count);
new RequestBuilder(oauth, "POST", "https://api.twitter.com/1.1/direct_messages/new.json")
.AddParameter("text", message)
.AddParameter("screen_name", screenName)
.Execute();
}
public IEnumerable<Tweet> 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<Tweet> GetMentions(long? sinceId = null, int? count = 20)
public IEnumerable<Tweet> GetMentions(long? sinceId = null, long? maxId = null, int? count = 20)
{
return GetTimeline("http://api.twitter.com/1.1/statuses/mentions.json", sinceId, count);
return GetTimeline("https://api.twitter.com/1.1/statuses/mentions.json", sinceId, maxId, count, "");
}
public IEnumerable<Tweet> GetUserTimeline(long? sinceId = null, int? count = 20)
public IEnumerable<Tweet> GetUserTimeline(long? sinceId = null, long? maxId = null, int? count = 20, string screenName = "")
{
return GetTimeline("http://api.twitter.com/1.1/statuses/user_timeline.json", sinceId, count);
return GetTimeline("https://api.twitter.com/1.1/statuses/user_timeline.json", sinceId, maxId, count, screenName);
}
private IEnumerable<Tweet> GetTimeline(string url, long? sinceId, int? count)
private IEnumerable<Tweet> 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());
using (var response = builder.Execute())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var content = reader.ReadToEnd();
if (screenName != "")
builder.AddParameter("screen_name", screenName);
var responseContent = builder.Execute();
var serializer = new JavaScriptSerializer();
var tweets = (object[])serializer.DeserializeObject(content);
var tweets = (object[])serializer.DeserializeObject(responseContent);
return tweets.Cast<Dictionary<string, object>>().Select(tweet =>
{
@ -84,18 +103,17 @@ namespace TinyTwitter
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,
CreatedAt = date,
Text = (string)tweet["text"],
UserName = (string)user["name"],
ScreenName = (string)user["screen_name"]
};
}).ToArray();
}
}
#region RequestBuilder
@ -123,7 +141,7 @@ namespace TinyTwitter
return this;
}
public WebResponse Execute()
public string Execute()
{
var timespan = GetTimestamp();
var nonce = CreateNonce();
@ -147,9 +165,20 @@ namespace TinyTwitter
// 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;
return content;
}
private void WriteRequestBody(HttpWebRequest request)

@ -2,6 +2,6 @@
<label class="col-sm-3 control-label"></label>
<div class="col-sm-5">
<button class="form-control x-path {{name}}" data-value="{{value}}">{{label}}</button>
<button class="form-control {{name}}" data-value="{{value}}">{{label}}</button>
</div>
</div>

@ -16,12 +16,10 @@ var view = Marionette.ItemView.extend({
onDownloadToggle : '.x-on-download',
onUpgradeSection : '.x-on-upgrade',
tags : '.x-tags',
indicator : '.x-indicator',
authorizedNotificationButton : '.AuthorizeNotification'
tags : '.x-tags',
modalBody : '.modal-body',
modalBody : '.x-modal-body',
formTag : '.x-form-tag',
path : '.x-path'
path : '.x-path',
authorizedNotificationButton : '.AuthorizeNotification'
},
events : {
@ -87,10 +85,13 @@ var view = Marionette.ItemView.extend({
}
},
_onAuthorizeNotification : function(e) {
_onAuthorizeNotification : function() {
var self = this;
self.ui.indicator.show();
this.model.connectData(this.ui.authorizedNotificationButton.data('value')).always(function(newValues) {
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();
});
}

@ -7,7 +7,7 @@
<h3>Add - {{implementationName}}</h3>
{{/if}}
</div>
<div class="modal-body notification-modal">
<div class="modal-body notification-modal x-modal">
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-3 control-label">Name</label>

@ -1,9 +1,10 @@
var $ = require('jquery');
var _ = require('underscore');
var DeepModel = require('backbone.deepmodel');
var Messenger = require('../Shared/Messenger');
module.exports = DeepModel.extend({
connectData : function(action) {
connectData : function(action, initialQueryString) {
var self = this;
this.trigger('connect:sync');
@ -11,45 +12,62 @@ module.exports = DeepModel.extend({
var promise = $.Deferred();
var callAction = function(action) {
var params = {};
params.url = self.collection.url + '/connectData/' + action;
params.contentType = 'application/json';
params.data = JSON.stringify(self.toJSON());
params.type = 'POST';
params.isValidatedCall = true;
var params = {
url : self.collection.url + '/connectData/' + action,
contentType : 'application/json',
data : JSON.stringify(self.toJSON()),
type : 'POST',
isValidatedCall : true
};
$.ajax(params).fail(promise.reject).success(function(response) {
var ajaxPromise = $.ajax(params);
ajaxPromise.fail(promise.reject);
ajaxPromise.success(function(response) {
if (response.action)
{
if (response.action === "openwindow")
if (response.action === 'openWindow')
{
var connectResponseWindow = window.open(response.url);
window.open(response.url);
var selfWindow = window;
selfWindow.onCompleteOauth = function(query, callback) {
delete selfWindow.onCompleteOauth;
if (response.nextStep) { callAction(response.nextStep + query); }
else { promise.resolve(response); }
if (response.nextStep) {
callAction(response.nextStep + query);
}
else {
promise.resolve(response);
}
callback();
};
return;
}
else if (response.action === "updatefields")
else if (response.action === 'updateFields')
{
Object.keys(response.fields).forEach(function(field) {
self.set(field, response.fields[field]);
self.attributes.fields.forEach(function(fieldDef) {
if (fieldDef.name === field) { fieldDef.value = response.fields[field]; }
_.each(self.get('fields'), function (value, index) {
var fieldValue = _.find(response.fields, function (field, key) {
return key === value.name;
});
if (fieldValue) {
self.set('fields.' + index + '.value', fieldValue);
}
});
}
}
if (response.nextStep) { callAction(response.nextStep); }
else { promise.resolve(response); }
if (response.nextStep) {
callAction(response.nextStep);
}
else {
promise.resolve(response);
}
});
};
callAction(action);
callAction(action, initialQueryString);
Messenger.monitor({
promise : promise,
@ -63,6 +81,7 @@ module.exports = DeepModel.extend({
return promise;
},
test : function() {
var self = this;

Loading…
Cancel
Save