From 4abf44617c296d659d5289355c9ea0ed8c17bcf2 Mon Sep 17 00:00:00 2001 From: Qstick Date: Wed, 8 Apr 2020 22:52:14 -0400 Subject: [PATCH] Convert Notifications from RestSharp to HttpClient --- .../Notifications/Boxcar/BoxcarProxy.cs | 36 +++---- .../Notifications/Discord/DiscordProxy.cs | 3 +- .../Notifications/Gotify/GotifyException.cs | 18 ++++ .../Notifications/Gotify/GotifyProxy.cs | 35 +++--- .../Gotify/InvalidResponseException.cs | 16 --- .../Notifications/Join/JoinProxy.cs | 42 ++++---- .../MediaBrowser/MediaBrowserService.cs | 4 +- .../Notifications/Prowl/ProwlProxy.cs | 34 +++--- .../PushBullet/PushBulletProxy.cs | 73 +++++++------ .../Notifications/Pushover/PushoverProxy.cs | 35 +++--- .../Notifications/Slack/SlackProxy.cs | 5 +- .../Notifications/Telegram/TelegramService.cs | 25 +++-- .../Notifications/Webhook/WebhookProxy.cs | 3 +- .../Notifications/Xbmc/XbmcJsonApiProxy.cs | 84 +++++---------- src/NzbDrone.Core/Radarr.Core.csproj | 1 - src/NzbDrone.Core/Rest/IRestClientFactory.cs | 9 -- src/NzbDrone.Core/Rest/JsonNetSerializer.cs | 23 ---- src/NzbDrone.Core/Rest/RestClientFactory.cs | 34 ------ src/NzbDrone.Core/Rest/RestException.cs | 26 ----- src/NzbDrone.Core/Rest/RestSharpExtensions.cs | 101 ------------------ 20 files changed, 201 insertions(+), 406 deletions(-) create mode 100644 src/NzbDrone.Core/Notifications/Gotify/GotifyException.cs delete mode 100644 src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs delete mode 100644 src/NzbDrone.Core/Rest/IRestClientFactory.cs delete mode 100644 src/NzbDrone.Core/Rest/JsonNetSerializer.cs delete mode 100644 src/NzbDrone.Core/Rest/RestClientFactory.cs delete mode 100644 src/NzbDrone.Core/Rest/RestException.cs delete mode 100644 src/NzbDrone.Core/Rest/RestSharpExtensions.cs diff --git a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs index 6f08caf57..1bc664209 100644 --- a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs +++ b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs @@ -1,10 +1,9 @@ -using System; +using System; using System.Net; using FluentValidation.Results; using NLog; using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Core.Rest; -using RestSharp; +using NzbDrone.Common.Http; namespace NzbDrone.Core.Notifications.Boxcar { @@ -17,22 +16,20 @@ public interface IBoxcarProxy public class BoxcarProxy : IBoxcarProxy { private const string URL = "https://new.boxcar.io/api/notifications"; - private readonly IRestClientFactory _restClientFactory; + private readonly IHttpClient _httpClient; private readonly Logger _logger; - public BoxcarProxy(IRestClientFactory restClientFactory, Logger logger) + public BoxcarProxy(IHttpClient httpClient, Logger logger) { - _restClientFactory = restClientFactory; + _httpClient = httpClient; _logger = logger; } public void SendNotification(string title, string message, BoxcarSettings settings) { - var request = new RestRequest(Method.POST); - try { - SendNotification(title, message, request, settings); + ProcessNotification(title, message, settings); } catch (BoxcarException ex) { @@ -51,7 +48,7 @@ public ValidationFailure Test(BoxcarSettings settings) SendNotification(title, body, settings); return null; } - catch (RestException ex) + catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.Unauthorized) { @@ -69,21 +66,22 @@ public ValidationFailure Test(BoxcarSettings settings) } } - private void SendNotification(string title, string message, RestRequest request, BoxcarSettings settings) + private void ProcessNotification(string title, string message, BoxcarSettings settings) { try { - var client = _restClientFactory.BuildClient(URL); + var requestBuilder = new HttpRequestBuilder(URL).Post(); - request.AddParameter("user_credentials", settings.Token); - request.AddParameter("notification[title]", title); - request.AddParameter("notification[long_message]", message); - request.AddParameter("notification[source_name]", BuildInfo.AppName); - request.AddParameter("notification[icon_url]", "https://raw.githubusercontent.com/Radarr/Radarr/develop/Logo/64.png"); + var request = requestBuilder.AddFormParameter("user_credentials", settings.Token) + .AddFormParameter("notification[title]", title) + .AddFormParameter("notification[long_message]", message) + .AddFormParameter("notification[source_name]", BuildInfo.AppName) + .AddFormParameter("notification[icon_url]", "https://raw.githubusercontent.com/Radarr/Radarr/develop/Logo/64.png") + .Build(); - client.ExecuteAndValidate(request); + _httpClient.Post(request); } - catch (RestException ex) + catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.Unauthorized) { diff --git a/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs b/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs index 37ecf794d..f3a6be3d2 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs @@ -2,7 +2,6 @@ using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; using NzbDrone.Core.Notifications.Discord.Payloads; -using NzbDrone.Core.Rest; namespace NzbDrone.Core.Notifications.Discord { @@ -36,7 +35,7 @@ public void SendPayload(DiscordPayload payload, DiscordSettings settings) _httpClient.Execute(request); } - catch (RestException ex) + catch (HttpException ex) { _logger.Error(ex, "Unable to post payload {0}", payload); throw new DiscordException("Unable to post payload", ex); diff --git a/src/NzbDrone.Core/Notifications/Gotify/GotifyException.cs b/src/NzbDrone.Core/Notifications/Gotify/GotifyException.cs new file mode 100644 index 000000000..35547460a --- /dev/null +++ b/src/NzbDrone.Core/Notifications/Gotify/GotifyException.cs @@ -0,0 +1,18 @@ +using System; +using NzbDrone.Common.Exceptions; + +namespace NzbDrone.Core.Notifications.Gotify +{ + public class GotifyException : NzbDroneException + { + public GotifyException(string message) + : base(message) + { + } + + public GotifyException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) + { + } + } +} diff --git a/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs b/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs index 15a1c40d4..c61147296 100644 --- a/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs +++ b/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Rest; -using RestSharp; +using System.Net; +using NzbDrone.Common.Http; namespace NzbDrone.Core.Notifications.Gotify { @@ -10,24 +10,35 @@ public interface IGotifyProxy public class GotifyProxy : IGotifyProxy { - private readonly IRestClientFactory _restClientFactory; + private readonly IHttpClient _httpClient; - public GotifyProxy(IRestClientFactory restClientFactory) + public GotifyProxy(IHttpClient httpClient) { - _restClientFactory = restClientFactory; + _httpClient = httpClient; } public void SendNotification(string title, string message, GotifySettings settings) { - var client = _restClientFactory.BuildClient(settings.Server); - var request = new RestRequest("message", Method.POST); + try + { + var request = new HttpRequestBuilder(settings.Server).Post() + .AddFormParameter("token", settings.AppToken) + .AddFormParameter("title", title) + .AddFormParameter("message", message) + .AddFormParameter("priority", settings.Priority) + .Build(); - request.AddQueryParameter("token", settings.AppToken); - request.AddParameter("title", title); - request.AddParameter("message", message); - request.AddParameter("priority", settings.Priority); + _httpClient.Post(request); + } + catch (HttpException ex) + { + if (ex.Response.StatusCode == HttpStatusCode.Unauthorized) + { + throw new GotifyException("Unauthorized - AuthToken is invalid"); + } - client.ExecuteAndValidate(request); + throw new GotifyException("Unable to connect to Gotify. Status Code: {0}", ex); + } } } } diff --git a/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs b/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs deleted file mode 100644 index acdc931f9..000000000 --- a/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace NzbDrone.Core.Notifications.Gotify -{ - public class InvalidResponseException : Exception - { - public InvalidResponseException() - { - } - - public InvalidResponseException(string message) - : base(message) - { - } - } -} diff --git a/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs b/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs index 81382cc4c..f0c976f83 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs @@ -2,9 +2,8 @@ using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; -using NzbDrone.Core.Rest; -using RestSharp; namespace NzbDrone.Core.Notifications.Join { @@ -17,22 +16,22 @@ public interface IJoinProxy public class JoinProxy : IJoinProxy { private const string URL = "https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?"; - private readonly IRestClientFactory _restClientFactory; + private readonly IHttpClient _httpClient; private readonly Logger _logger; - public JoinProxy(IRestClientFactory restClientFactory, Logger logger) + public JoinProxy(IHttpClient httpClient, Logger logger) { - _restClientFactory = restClientFactory; + _httpClient = httpClient; _logger = logger; } public void SendNotification(string title, string message, JoinSettings settings) { - var request = new RestRequest(Method.GET); + var method = HttpMethod.GET; try { - SendNotification(title, message, request, settings); + SendNotification(title, message, method, settings); } catch (JoinException ex) { @@ -61,7 +60,7 @@ public ValidationFailure Test(JoinSettings settings) _logger.Error(ex, "Unable to send test Join message."); return new ValidationFailure("ApiKey", ex.Message); } - catch (RestException ex) + catch (HttpException ex) { _logger.Error(ex, "Unable to send test Join message. Server connection failed."); return new ValidationFailure("ApiKey", "Unable to connect to Join API. Please try again later."); @@ -73,31 +72,34 @@ public ValidationFailure Test(JoinSettings settings) } } - private void SendNotification(string title, string message, RestRequest request, JoinSettings settings) + private void SendNotification(string title, string message, HttpMethod method, JoinSettings settings) { - var client = _restClientFactory.BuildClient(URL); + var requestBuilder = new HttpRequestBuilder(URL); if (settings.DeviceNames.IsNotNullOrWhiteSpace()) { - request.AddParameter("deviceNames", settings.DeviceNames); + requestBuilder.AddQueryParam("deviceNames", settings.DeviceNames); } else if (settings.DeviceIds.IsNotNullOrWhiteSpace()) { - request.AddParameter("deviceIds", settings.DeviceIds); + requestBuilder.AddQueryParam("deviceIds", settings.DeviceIds); } else { - request.AddParameter("deviceId", "group.all"); + requestBuilder.AddQueryParam("deviceId", "group.all"); } - request.AddParameter("apikey", settings.ApiKey); - request.AddParameter("title", title); - request.AddParameter("text", message); - request.AddParameter("icon", "https://cdn.rawgit.com/Radarr/Radarr/develop/Logo/256.png"); // Use the Radarr logo. - request.AddParameter("smallicon", "https://cdn.rawgit.com/Radarr/Radarr/develop/Logo/96-Outline-White.png"); // 96x96px with outline at 88x88px on a transparent background. - request.AddParameter("priority", settings.Priority); + var request = requestBuilder.AddQueryParam("apikey", settings.ApiKey) + .AddQueryParam("title", title) + .AddQueryParam("text", message) + .AddQueryParam("icon", "https://cdn.rawgit.com/Radarr/Radarr/develop/Logo/256.png") // Use the Radarr logo. + .AddQueryParam("smallicon", "https://cdn.rawgit.com/Radarr/Radarr/develop/Logo/96-Outline-White.png") // 96x96px with outline at 88x88px on a transparent background. + .AddQueryParam("priority", settings.Priority) + .Build(); - var response = client.ExecuteAndValidate(request); + request.Method = method; + + var response = _httpClient.Execute(request); var res = Json.Deserialize(response.Content); if (res.success) diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs index 62565a9b2..3ff3b1f2f 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs @@ -2,8 +2,8 @@ using System.Net; using FluentValidation.Results; using NLog; +using NzbDrone.Common.Http; using NzbDrone.Core.Movies; -using NzbDrone.Core.Rest; namespace NzbDrone.Core.Notifications.Emby { @@ -43,7 +43,7 @@ public ValidationFailure Test(MediaBrowserSettings settings) Notify(settings, "Test from Radarr", "Success! MediaBrowser has been successfully configured!"); } - catch (RestException ex) + catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.Unauthorized) { diff --git a/src/NzbDrone.Core/Notifications/Prowl/ProwlProxy.cs b/src/NzbDrone.Core/Notifications/Prowl/ProwlProxy.cs index 5998acc78..3a88603fe 100644 --- a/src/NzbDrone.Core/Notifications/Prowl/ProwlProxy.cs +++ b/src/NzbDrone.Core/Notifications/Prowl/ProwlProxy.cs @@ -3,8 +3,7 @@ using FluentValidation.Results; using NLog; using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Core.Rest; -using RestSharp; +using NzbDrone.Common.Http; namespace NzbDrone.Core.Notifications.Prowl { @@ -17,12 +16,12 @@ public interface IProwlProxy public class ProwlProxy : IProwlProxy { private const string PUSH_URL = "https://api.prowlapp.com/publicapi/add"; - private readonly IRestClientFactory _restClientFactory; + private readonly IHttpClient _httpClient; private readonly Logger _logger; - public ProwlProxy(IRestClientFactory restClientFactory, Logger logger) + public ProwlProxy(IHttpClient httpClient, Logger logger) { - _restClientFactory = restClientFactory; + _httpClient = httpClient; _logger = logger; } @@ -30,19 +29,20 @@ public void SendNotification(string title, string message, string apiKey, ProwlP { try { - var client = _restClientFactory.BuildClient(PUSH_URL); - var request = new RestRequest(Method.POST); + var requestBuilder = new HttpRequestBuilder(PUSH_URL); - request.AddParameter("apikey", apiKey); - request.AddParameter("application", BuildInfo.AppName); - request.AddParameter("event", title); - request.AddParameter("description", message); - request.AddParameter("priority", priority); - request.AddParameter("url", url); + var request = requestBuilder.Post() + .AddFormParameter("apikey", apiKey) + .AddFormParameter("application", BuildInfo.AppName) + .AddFormParameter("event", title) + .AddFormParameter("description", message) + .AddFormParameter("priority", priority) + .AddFormParameter("url", url) + .Build(); - client.ExecuteAndValidate(request); + _httpClient.Post(request); } - catch (RestException ex) + catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.Unauthorized) { @@ -52,6 +52,10 @@ public void SendNotification(string title, string message, string apiKey, ProwlP throw new ProwlException("Unable to send text message: " + ex.Message, ex); } + catch (WebException ex) + { + throw new ProwlException("Failed to connect to prowl, please check your settings.", ex); + } } public ValidationFailure Test(ProwlSettings settings) diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs index 5cc9867b8..e66aac0ef 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs @@ -5,10 +5,8 @@ using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; -using NzbDrone.Core.Rest; -using RestSharp; -using RestSharp.Authenticators; namespace NzbDrone.Core.Notifications.PushBullet { @@ -23,12 +21,12 @@ public class PushBulletProxy : IPushBulletProxy { private const string PUSH_URL = "https://api.pushbullet.com/v2/pushes"; private const string DEVICE_URL = "https://api.pushbullet.com/v2/devices"; - private readonly IRestClientFactory _restClientFactory; + private readonly IHttpClient _httpClient; private readonly Logger _logger; - public PushBulletProxy(IRestClientFactory restClientFactory, Logger logger) + public PushBulletProxy(IHttpClient httpClient, Logger logger) { - _restClientFactory = restClientFactory; + _httpClient = httpClient; _logger = logger; } @@ -98,15 +96,18 @@ public List GetDevices(PushBulletSettings settings) { try { - var client = _restClientFactory.BuildClient(DEVICE_URL); - var request = new RestRequest(Method.GET); + var requestBuilder = new HttpRequestBuilder(DEVICE_URL); - client.Authenticator = new HttpBasicAuthenticator(settings.ApiKey, string.Empty); - var response = client.ExecuteAndValidate(request); + var request = requestBuilder.Build(); + + request.Method = HttpMethod.GET; + request.AddBasicAuthentication(settings.ApiKey, string.Empty); + + var response = _httpClient.Execute(request); return Json.Deserialize(response.Content).Devices; } - catch (RestException ex) + catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.Unauthorized) { @@ -127,7 +128,7 @@ public ValidationFailure Test(PushBulletSettings settings) SendNotification(title, body, settings); } - catch (RestException ex) + catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.Unauthorized) { @@ -147,50 +148,60 @@ public ValidationFailure Test(PushBulletSettings settings) return null; } - private RestRequest BuildDeviceRequest(string deviceId) + private HttpRequestBuilder BuildDeviceRequest(string deviceId) { - var request = new RestRequest(Method.POST); + var requestBuilder = new HttpRequestBuilder(PUSH_URL).Post(); long integerId; + if (deviceId.IsNullOrWhiteSpace()) + { + return requestBuilder; + } + if (long.TryParse(deviceId, out integerId)) { - request.AddParameter("device_id", integerId); + requestBuilder.AddFormParameter("device_id", integerId); } else { - request.AddParameter("device_iden", deviceId); + requestBuilder.AddFormParameter("device_iden", deviceId); } - return request; + return requestBuilder; } - private RestRequest BuildChannelRequest(string channelTag) + private HttpRequestBuilder BuildChannelRequest(string channelTag) { - var request = new RestRequest(Method.POST); - request.AddParameter("channel_tag", channelTag); + var requestBuilder = new HttpRequestBuilder(PUSH_URL).Post(); - return request; + if (channelTag.IsNotNullOrWhiteSpace()) + { + requestBuilder.AddFormParameter("channel_tag", channelTag); + } + + return requestBuilder; } - private void SendNotification(string title, string message, RestRequest request, PushBulletSettings settings) + private void SendNotification(string title, string message, HttpRequestBuilder requestBuilder, PushBulletSettings settings) { try { - var client = _restClientFactory.BuildClient(PUSH_URL); - - request.AddParameter("type", "note"); - request.AddParameter("title", title); - request.AddParameter("body", message); + requestBuilder.AddFormParameter("type", "note") + .AddFormParameter("title", title) + .AddFormParameter("body", message); if (settings.SenderId.IsNotNullOrWhiteSpace()) { - request.AddParameter("source_device_iden", settings.SenderId); + requestBuilder.AddFormParameter("source_device_iden", settings.SenderId); } - client.Authenticator = new HttpBasicAuthenticator(settings.ApiKey, string.Empty); - client.ExecuteAndValidate(request); + var request = requestBuilder.Build(); + + request.AddBasicAuthentication(settings.ApiKey, string.Empty); + + _httpClient.Execute(request); } - catch (RestException ex) + catch (HttpException ex) { if (ex.Response.StatusCode == HttpStatusCode.Unauthorized) { diff --git a/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs b/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs index ea32f0efc..ef415ffbf 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/PushoverProxy.cs @@ -2,8 +2,7 @@ using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Rest; -using RestSharp; +using NzbDrone.Common.Http; namespace NzbDrone.Core.Notifications.Pushover { @@ -16,38 +15,40 @@ public interface IPushoverProxy public class PushoverProxy : IPushoverProxy { private const string URL = "https://api.pushover.net/1/messages.json"; - private readonly IRestClientFactory _restClientFactory; + private readonly IHttpClient _httpClient; private readonly Logger _logger; - public PushoverProxy(IRestClientFactory restClientFactory, Logger logger) + public PushoverProxy(IHttpClient httpClient, Logger logger) { - _restClientFactory = restClientFactory; + _httpClient = httpClient; _logger = logger; } public void SendNotification(string title, string message, PushoverSettings settings) { - var client = _restClientFactory.BuildClient(URL); - var request = new RestRequest(Method.POST); - request.AddParameter("token", settings.ApiKey); - request.AddParameter("user", settings.UserKey); - request.AddParameter("device", string.Join(",", settings.Devices)); - request.AddParameter("title", title); - request.AddParameter("message", message); - request.AddParameter("priority", settings.Priority); + var requestBuilder = new HttpRequestBuilder(URL).Post(); + + requestBuilder.AddFormParameter("token", settings.ApiKey) + .AddFormParameter("user", settings.UserKey) + .AddFormParameter("device", string.Join(",", settings.Devices)) + .AddFormParameter("title", title) + .AddFormParameter("message", message) + .AddFormParameter("priority", settings.Priority); if ((PushoverPriority)settings.Priority == PushoverPriority.Emergency) { - request.AddParameter("retry", settings.Retry); - request.AddParameter("expire", settings.Expire); + requestBuilder.AddFormParameter("retry", settings.Retry); + requestBuilder.AddFormParameter("expire", settings.Expire); } if (!settings.Sound.IsNullOrWhiteSpace()) { - request.AddParameter("sound", settings.Sound); + requestBuilder.AddFormParameter("sound", settings.Sound); } - client.ExecuteAndValidate(request); + var request = requestBuilder.Build(); + + _httpClient.Post(request); } public ValidationFailure Test(PushoverSettings settings) diff --git a/src/NzbDrone.Core/Notifications/Slack/SlackProxy.cs b/src/NzbDrone.Core/Notifications/Slack/SlackProxy.cs index d612cf012..02075dad9 100644 --- a/src/NzbDrone.Core/Notifications/Slack/SlackProxy.cs +++ b/src/NzbDrone.Core/Notifications/Slack/SlackProxy.cs @@ -1,8 +1,7 @@ -using NLog; +using NLog; using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; using NzbDrone.Core.Notifications.Slack.Payloads; -using NzbDrone.Core.Rest; namespace NzbDrone.Core.Notifications.Slack { @@ -36,7 +35,7 @@ public void SendPayload(SlackPayload payload, SlackSettings settings) _httpClient.Execute(request); } - catch (RestException ex) + catch (HttpException ex) { _logger.Error(ex, "Unable to post payload {0}", payload); throw new SlackExeption("Unable to post payload", ex); diff --git a/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs b/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs index 16658f0c3..6c43a7292 100644 --- a/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs +++ b/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs @@ -4,9 +4,8 @@ using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; -using NzbDrone.Core.Rest; -using RestSharp; namespace NzbDrone.Core.Notifications.Telegram { @@ -19,12 +18,12 @@ public interface ITelegramProxy public class TelegramProxy : ITelegramProxy { private const string URL = "https://api.telegram.org"; - private readonly IRestClientFactory _restClientFactory; + private readonly IHttpClient _httpClient; private readonly Logger _logger; - public TelegramProxy(IRestClientFactory restClientFactory, Logger logger) + public TelegramProxy(IHttpClient httpClient, Logger logger) { - _restClientFactory = restClientFactory; + _httpClient = httpClient; _logger = logger; } @@ -32,16 +31,16 @@ public void SendNotification(string title, string message, TelegramSettings sett { //Format text to add the title before and bold using markdown var text = $"{HttpUtility.HtmlEncode(title)}\n{HttpUtility.HtmlEncode(message)}"; - var client = _restClientFactory.BuildClient(URL); - var request = new RestRequest("bot{token}/sendmessage", Method.POST); + var requestBuilder = new HttpRequestBuilder(URL).Resource("bot{token}/sendmessage").Post(); - request.AddUrlSegment("token", settings.BotToken); - request.AddParameter("chat_id", settings.ChatId); - request.AddParameter("parse_mode", "HTML"); - request.AddParameter("text", text); + var request = requestBuilder.SetSegment("token", settings.BotToken) + .AddFormParameter("chat_id", settings.ChatId) + .AddFormParameter("parse_mode", "HTML") + .AddFormParameter("text", text) + .Build(); - client.ExecuteAndValidate(request); + _httpClient.Post(request); } public ValidationFailure Test(TelegramSettings settings) @@ -61,7 +60,7 @@ public ValidationFailure Test(TelegramSettings settings) { return new ValidationFailure("Connection", $"{webException.Status.ToString()}: {webException.Message}"); } - else if (ex is RestException restException && restException.Response.StatusCode == HttpStatusCode.BadRequest) + else if (ex is Common.Http.HttpException restException && restException.Response.StatusCode == HttpStatusCode.BadRequest) { var error = Json.Deserialize(restException.Response.Content); var property = error.Description.ContainsIgnoreCase("chat not found") ? "ChatId" : "BotToken"; diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs index f7eedec69..489eeb41f 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs @@ -1,7 +1,6 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; -using NzbDrone.Core.Rest; namespace NzbDrone.Core.Notifications.Webhook { @@ -38,7 +37,7 @@ public void SendWebhook(WebhookPayload body, WebhookSettings settings) _httpClient.Execute(request); } - catch (RestException ex) + catch (HttpException ex) { throw new WebhookException("Unable to post to webhook: {0}", ex, ex.Message); } diff --git a/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs b/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs index ae6923f9b..5f17a0373 100644 --- a/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs +++ b/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs @@ -1,11 +1,9 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; using NzbDrone.Core.Notifications.Xbmc.Model; -using NzbDrone.Core.Rest; -using RestSharp; -using RestSharp.Authenticators; namespace NzbDrone.Core.Notifications.Xbmc { @@ -21,87 +19,66 @@ public interface IXbmcJsonApiProxy public class XbmcJsonApiProxy : IXbmcJsonApiProxy { - private readonly IRestClientFactory _restClientFactory; + private readonly IHttpClient _httpClient; private readonly Logger _logger; - public XbmcJsonApiProxy(IRestClientFactory restClientFactory, Logger logger) + public XbmcJsonApiProxy(IHttpClient httpClient, Logger logger) { - _restClientFactory = restClientFactory; + _httpClient = httpClient; _logger = logger; } public string GetJsonVersion(XbmcSettings settings) { - var request = new RestRequest(); - return ProcessRequest(request, settings, "JSONRPC.Version"); + return ProcessRequest(settings, "JSONRPC.Version"); } public void Notify(XbmcSettings settings, string title, string message) { - var request = new RestRequest(); - - var parameters = new Dictionary(); - parameters.Add("title", title); - parameters.Add("message", message); - parameters.Add("image", "https://raw.github.com/Radarr/Radarr/develop/Logo/64.png"); - parameters.Add("displaytime", settings.DisplayTime * 1000); - - ProcessRequest(request, settings, "GUI.ShowNotification", parameters); + ProcessRequest(settings, "GUI.ShowNotification", title, message, "https://raw.github.com/Radarr/Radarr/develop/Logo/64.png", settings.DisplayTime * 1000); } public string UpdateLibrary(XbmcSettings settings, string path) { - var request = new RestRequest(); - var parameters = new Dictionary(); - parameters.Add("directory", path); - - if (path.IsNullOrWhiteSpace()) - { - parameters = null; - } - - var response = ProcessRequest(request, settings, "VideoLibrary.Scan", parameters); + var response = ProcessRequest(settings, "VideoLibrary.Scan", path); return Json.Deserialize>(response).Result; } public void CleanLibrary(XbmcSettings settings) { - var request = new RestRequest(); - - ProcessRequest(request, settings, "VideoLibrary.Clean"); + ProcessRequest(settings, "VideoLibrary.Clean"); } public List GetActivePlayers(XbmcSettings settings) { - var request = new RestRequest(); - - var response = ProcessRequest(request, settings, "Player.GetActivePlayers"); + var response = ProcessRequest(settings, "Player.GetActivePlayers"); return Json.Deserialize(response).Result; } public List GetMovies(XbmcSettings settings) { - var request = new RestRequest(); - var parameters = new Dictionary(); - parameters.Add("properties", new[] { "file", "imdbnumber" }); - - var response = ProcessRequest(request, settings, "VideoLibrary.GetMovies", parameters); + var response = ProcessRequest(settings, "VideoLibrary.GetMovies", new[] { "file", "imdbnumber" }); return Json.Deserialize(response).Result.Movies; } - private string ProcessRequest(IRestRequest request, XbmcSettings settings, string method, Dictionary parameters = null) + private string ProcessRequest(XbmcSettings settings, string method, params object[] parameters) { - var client = BuildClient(settings); + var url = string.Format(@"http://{0}/jsonrpc", settings.Address); + var requestBuilder = new JsonRpcRequestBuilder(url, method, parameters); - request.Method = Method.POST; - request.RequestFormat = DataFormat.Json; - request.JsonSerializer = new JsonNetSerializer(); - request.AddBody(new { jsonrpc = "2.0", method = method, id = 10, @params = parameters }); + requestBuilder.LogResponseContent = true; - var response = client.ExecuteAndValidate(request); + var request = requestBuilder.Build(); + + if (!settings.Username.IsNullOrWhiteSpace()) + { + request.AddBasicAuthentication(settings.Username, settings.Password); + } + + var response = _httpClient.Execute(request); _logger.Trace("Response: {0}", response.Content); CheckForError(response); @@ -109,20 +86,7 @@ private string ProcessRequest(IRestRequest request, XbmcSettings settings, strin return response.Content; } - private IRestClient BuildClient(XbmcSettings settings) - { - var url = string.Format(@"http://{0}/jsonrpc", settings.Address); - var client = _restClientFactory.BuildClient(url); - - if (!settings.Username.IsNullOrWhiteSpace()) - { - client.Authenticator = new HttpBasicAuthenticator(settings.Username, settings.Password); - } - - return client; - } - - private void CheckForError(IRestResponse response) + private void CheckForError(HttpResponse response) { if (string.IsNullOrWhiteSpace(response.Content)) { diff --git a/src/NzbDrone.Core/Radarr.Core.csproj b/src/NzbDrone.Core/Radarr.Core.csproj index 542f50264..ecfd8a5b7 100644 --- a/src/NzbDrone.Core/Radarr.Core.csproj +++ b/src/NzbDrone.Core/Radarr.Core.csproj @@ -13,7 +13,6 @@ - diff --git a/src/NzbDrone.Core/Rest/IRestClientFactory.cs b/src/NzbDrone.Core/Rest/IRestClientFactory.cs deleted file mode 100644 index 39754016d..000000000 --- a/src/NzbDrone.Core/Rest/IRestClientFactory.cs +++ /dev/null @@ -1,9 +0,0 @@ -using RestSharp; - -namespace NzbDrone.Core.Rest -{ - public interface IRestClientFactory - { - RestClient BuildClient(string baseUrl); - } -} diff --git a/src/NzbDrone.Core/Rest/JsonNetSerializer.cs b/src/NzbDrone.Core/Rest/JsonNetSerializer.cs deleted file mode 100644 index e5bcdfb3a..000000000 --- a/src/NzbDrone.Core/Rest/JsonNetSerializer.cs +++ /dev/null @@ -1,23 +0,0 @@ -using NzbDrone.Common.Serializer; -using RestSharp.Serializers; - -namespace NzbDrone.Core.Rest -{ - public class JsonNetSerializer : ISerializer - { - public JsonNetSerializer() - { - ContentType = "application/json"; - } - - public string Serialize(object obj) - { - return obj.ToJson(); - } - - public string RootElement { get; set; } - public string Namespace { get; set; } - public string DateFormat { get; set; } - public string ContentType { get; set; } - } -} diff --git a/src/NzbDrone.Core/Rest/RestClientFactory.cs b/src/NzbDrone.Core/Rest/RestClientFactory.cs deleted file mode 100644 index 2614840c8..000000000 --- a/src/NzbDrone.Core/Rest/RestClientFactory.cs +++ /dev/null @@ -1,34 +0,0 @@ -using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Common.Http.Proxy; -using RestSharp; - -namespace NzbDrone.Core.Rest -{ - public class RestClientFactory : IRestClientFactory - { - private readonly IHttpProxySettingsProvider _httpProxySettingsProvider; - private readonly ICreateManagedWebProxy _createManagedWebProxy; - - public RestClientFactory(IHttpProxySettingsProvider httpProxySettingsProvider, ICreateManagedWebProxy createManagedWebProxy) - { - _httpProxySettingsProvider = httpProxySettingsProvider; - _createManagedWebProxy = createManagedWebProxy; - } - - public RestClient BuildClient(string baseUrl) - { - var restClient = new RestClient(baseUrl) - { - UserAgent = $"{BuildInfo.AppName}/{BuildInfo.Version} ({OsInfo.Os})" - }; - - var proxySettings = _httpProxySettingsProvider.GetProxySettings(); - if (proxySettings != null) - { - restClient.Proxy = _createManagedWebProxy.GetWebProxy(proxySettings); - } - - return restClient; - } - } -} diff --git a/src/NzbDrone.Core/Rest/RestException.cs b/src/NzbDrone.Core/Rest/RestException.cs deleted file mode 100644 index 99a0be97a..000000000 --- a/src/NzbDrone.Core/Rest/RestException.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using RestSharp; - -namespace NzbDrone.Core.Rest -{ - public class RestException : Exception - { - public IRestResponse Response { get; private set; } - - public RestException(IRestResponse response, IRestClient restClient) - : base(string.Format("REST request failed: [{0}] [{1}] at [{2}]", (int)response.StatusCode, response.Request.Method, restClient.BuildUri(response.Request))) - { - Response = response; - } - - public override string ToString() - { - if (Response != null) - { - return base.ToString() + Environment.NewLine + Response.Content; - } - - return base.ToString(); - } - } -} diff --git a/src/NzbDrone.Core/Rest/RestSharpExtensions.cs b/src/NzbDrone.Core/Rest/RestSharpExtensions.cs deleted file mode 100644 index 938b8723d..000000000 --- a/src/NzbDrone.Core/Rest/RestSharpExtensions.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System.Linq; -using System.Net; -using NLog; -using NzbDrone.Common.EnsureThat; -using NzbDrone.Common.Instrumentation; -using NzbDrone.Common.Serializer; -using RestSharp; - -namespace NzbDrone.Core.Rest -{ - public static class RestSharpExtensions - { - private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(RestSharpExtensions)); - - public static IRestResponse ValidateResponse(this IRestResponse response, IRestClient restClient) - { - Ensure.That(response, () => response).IsNotNull(); - - if (response.Request == null && response.ErrorException != null) - { - throw response.ErrorException; - } - - Ensure.That(response.Request, () => response.Request).IsNotNull(); - Ensure.That(restClient, () => restClient).IsNotNull(); - - Logger.Debug("Validating Responses from [{0}] [{1}] status: [{2}]", response.Request.Method, restClient.BuildUri(response.Request), response.StatusCode); - - if (response.ResponseUri == null) - { - Logger.Error(response.ErrorException, "Error communicating with server"); - throw response.ErrorException; - } - - switch (response.StatusCode) - { - case HttpStatusCode.OK: - { - return response; - } - - case HttpStatusCode.NoContent: - { - return response; - } - - case HttpStatusCode.Created: - { - return response; - } - - default: - { - Logger.Warn("[{0}] [{1}] Failed. [{2}]", response.Request.Method, response.ResponseUri.ToString(), response.StatusCode); - throw new RestException(response, restClient); - } - } - } - - public static T Read(this IRestResponse restResponse, IRestClient restClient) - where T : class, new() - { - restResponse.ValidateResponse(restClient); - - if (restResponse.Content != null) - { - Logger.Trace("Response: " + restResponse.Content); - } - - return Json.Deserialize(restResponse.Content); - } - - public static T ExecuteAndValidate(this IRestClient client, IRestRequest request) - where T : class, new() - { - return client.Execute(request).Read(client); - } - - public static IRestResponse ExecuteAndValidate(this IRestClient client, IRestRequest request) - { - return client.Execute(request).ValidateResponse(client); - } - - public static void AddQueryString(this IRestRequest request, string name, object value) - { - request.AddParameter(name, value.ToString(), ParameterType.GetOrPost); - } - - public static object GetHeaderValue(this IRestResponse response, string key) - { - var header = response.Headers.FirstOrDefault(v => v.Name == key); - - if (header == null) - { - return null; - } - - return header.Value; - } - } -}