#254 MOSTLY DONE! At last, this took a while.

So currently if a series exists then we will correctly monitor the episodes selected.

TODO: When the series doesn't exist in sonarr we need to add the series and then wait for the episode metadata to be populated.

Also need to add in all of the regular checks  and notification e.g. whitelist etc.
This commit is contained in:
tidusjar 2016-07-24 18:02:43 +01:00
commit b14fd36ecd
21 changed files with 1380 additions and 861 deletions

View file

@ -63,11 +63,11 @@ namespace PlexRequests.Api
request.AddUrlSegment("imdbid", imdbid);
request.AddUrlSegment("title", title);
var obj = RetryHandler.Execute(() => Api.ExecuteJson<JObject>(request, baseUrl), new[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)},
(exception, timespan) => Log.Error(exception, "Exception when calling AddMovie for CP, Retrying {0}", timespan));
var obj = RetryHandler.Execute(() => Api.ExecuteJson<JObject>(request, baseUrl),
(exception, timespan) => Log.Error(exception, "Exception when calling AddMovie for CP, Retrying {0}", timespan), new[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)});
if (obj.Count > 0)
@ -103,11 +103,11 @@ namespace PlexRequests.Api
request.AddUrlSegment("apikey", apiKey);
var obj = RetryHandler.Execute<CouchPotatoStatus>(() => Api.Execute<CouchPotatoStatus>(request, url), new TimeSpan[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)},
(exception, timespan) => Log.Error(exception, "Exception when calling GetStatus for CP, Retrying {0}", timespan));
var obj = RetryHandler.Execute<CouchPotatoStatus>(() => Api.Execute<CouchPotatoStatus>(request, url),
(exception, timespan) => Log.Error(exception, "Exception when calling GetStatus for CP, Retrying {0}", timespan), new TimeSpan[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)});
return obj;
}
@ -122,8 +122,8 @@ namespace PlexRequests.Api
request.AddUrlSegment("apikey", apiKey);
var obj = RetryHandler.Execute(() => Api.Execute<CouchPotatoProfiles>(request, url), null,
(exception, timespan) => Log.Error(exception, "Exception when calling GetProfiles for CP, Retrying {0}", timespan));
var obj = RetryHandler.Execute(() => Api.Execute<CouchPotatoProfiles>(request, url),
(exception, timespan) => Log.Error(exception, "Exception when calling GetProfiles for CP, Retrying {0}", timespan), null);
return obj;
}
@ -144,12 +144,11 @@ namespace PlexRequests.Api
try
{
var obj = RetryHandler.Execute(() => Api.Execute<CouchPotatoMovies>(request, baseUrl),
new[] {
(exception, timespan) => Log.Error(exception, "Exception when calling GetMovies for CP, Retrying {0}", timespan), new[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
},
(exception, timespan) => Log.Error(exception, "Exception when calling GetMovies for CP, Retrying {0}", timespan));
});
return obj;
}
@ -172,8 +171,8 @@ namespace PlexRequests.Api
request.AddUrlSegment("username", StringHasher.CalcuateMd5Hash(username));
request.AddUrlSegment("password", StringHasher.CalcuateMd5Hash(password));
var obj = RetryHandler.Execute(() => Api.Execute<CoucPotatoApiKey>(request, baseUrl), null,
(exception, timespan) => Log.Error(exception, "Exception when calling GetApiKey for CP, Retrying {0}", timespan));
var obj = RetryHandler.Execute(() => Api.Execute<CoucPotatoApiKey>(request, baseUrl),
(exception, timespan) => Log.Error(exception, "Exception when calling GetApiKey for CP, Retrying {0}", timespan), null);
return obj;
}

View file

@ -1,64 +1,89 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: MockSonarrApi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Sonarr;
namespace PlexRequests.Api.Mocks
{
public class MockSonarrApi : ISonarrApi
{
public List<SonarrProfile> GetProfiles(string apiKey, Uri baseUrl)
{
var json = MockApiData.Sonarr_Profiles;
var obj = JsonConvert.DeserializeObject<List<SonarrProfile>>(json);
return obj;
}
public SonarrAddSeries AddSeries(int tvdbId, string title, int qualityId, bool seasonFolders, string rootPath, int seasonCount, int[] seasons,
string apiKey, Uri baseUrl)
{
var json = MockApiData.Sonarr_AddSeriesResult;
var obj = JsonConvert.DeserializeObject<SonarrAddSeries>(json);
return obj;
}
public SystemStatus SystemStatus(string apiKey, Uri baseUrl)
{
throw new NotImplementedException();
}
public List<Series> GetSeries(string apiKey, Uri baseUrl)
{
throw new NotImplementedException();
}
}
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: MockSonarrApi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Sonarr;
namespace PlexRequests.Api.Mocks
{
public class MockSonarrApi : ISonarrApi
{
public List<SonarrProfile> GetProfiles(string apiKey, Uri baseUrl)
{
var json = MockApiData.Sonarr_Profiles;
var obj = JsonConvert.DeserializeObject<List<SonarrProfile>>(json);
return obj;
}
public SonarrAddSeries AddSeries(int tvdbId, string title, int qualityId, bool seasonFolders, string rootPath, int seasonCount, int[] seasons,
string apiKey, Uri baseUrl)
{
var json = MockApiData.Sonarr_AddSeriesResult;
var obj = JsonConvert.DeserializeObject<SonarrAddSeries>(json);
return obj;
}
public SystemStatus SystemStatus(string apiKey, Uri baseUrl)
{
throw new NotImplementedException();
}
public List<Series> GetSeries(string apiKey, Uri baseUrl)
{
throw new NotImplementedException();
}
public Series GetSeries(string seriesId, string apiKey, Uri baseUrl)
{
throw new NotImplementedException();
}
public IEnumerable<SonarrEpisodes> GetEpisodes(string seriesId, string apiKey, Uri baseUrl)
{
throw new NotImplementedException();
}
public SonarrEpisode GetEpisode(string episodeId, string apiKey, Uri baseUrl)
{
throw new NotImplementedException();
}
public SonarrEpisode UpdateEpisode(SonarrEpisode episodeInfo, string apiKey, Uri baseUrl)
{
throw new NotImplementedException();
}
public SonarrAddEpisodeResult SearchForEpisodes(int[] episodeIds, string apiKey, Uri baseUrl)
{
throw new NotImplementedException();
}
}
}

View file

@ -1,268 +1,260 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: PlexApi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
using Polly;
#endregion
using System;
using NLog;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Plex;
using PlexRequests.Helpers;
using PlexRequests.Helpers.Exceptions;
using RestSharp;
namespace PlexRequests.Api
{
public class PlexApi : IPlexApi
{
static PlexApi()
{
Version = AssemblyHelper.GetAssemblyVersion();
}
public PlexApi (IApiRequest api)
{
Api = api;
}
private IApiRequest Api { get; }
private const string SignInUri = "https://plex.tv/users/sign_in.json";
private const string FriendsUri = "https://plex.tv/pms/friends/all";
private const string GetAccountUri = "https://plex.tv/users/account";
private static Logger Log = LogManager.GetCurrentClassLogger();
private static string Version { get; }
public PlexAuthentication SignIn(string username, string password)
{
var userModel = new PlexUserRequest
{
user = new UserRequest
{
password = password,
login = username
}
};
var request = new RestRequest
{
Method = Method.POST
};
AddHeaders(ref request);
request.AddJsonBody(userModel);
var obj = RetryHandler.Execute<PlexAuthentication>(() => Api.Execute<PlexAuthentication> (request, new Uri(SignInUri)),
null,
(exception, timespan) => Log.Error (exception, "Exception when calling SignIn for Plex, Retrying {0}", timespan));
return obj;
}
public PlexFriends GetUsers(string authToken)
{
var request = new RestRequest
{
Method = Method.GET,
};
AddHeaders(ref request, authToken);
var users = RetryHandler.Execute(() => Api.ExecuteXml<PlexFriends> (request, new Uri(FriendsUri)),
null,
(exception, timespan) => Log.Error (exception, "Exception when calling GetUsers for Plex, Retrying {0}", timespan));
return users;
}
/// <summary>
/// Gets the users.
/// </summary>
/// <param name="authToken">The authentication token.</param>
/// <param name="searchTerm">The search term.</param>
/// <param name="plexFullHost">The full plex host.</param>
/// <returns></returns>
public PlexSearch SearchContent(string authToken, string searchTerm, Uri plexFullHost)
{
var request = new RestRequest
{
Method = Method.GET,
Resource = "search?query={searchTerm}"
};
request.AddUrlSegment("searchTerm", searchTerm);
AddHeaders(ref request, authToken);
var search = RetryHandler.Execute<PlexSearch>(() => Api.ExecuteXml<PlexSearch> (request, plexFullHost),
null,
(exception, timespan) => Log.Error (exception, "Exception when calling SearchContent for Plex, Retrying {0}", timespan));
return search;
}
public PlexStatus GetStatus(string authToken, Uri uri)
{
var request = new RestRequest
{
Method = Method.GET,
};
AddHeaders(ref request, authToken);
var users = RetryHandler.Execute<PlexStatus>(() => Api.ExecuteXml<PlexStatus> (request, uri),
null,
(exception, timespan) => Log.Error (exception, "Exception when calling GetStatus for Plex, Retrying {0}", timespan));
return users;
}
public PlexAccount GetAccount(string authToken)
{
var request = new RestRequest
{
Method = Method.GET,
};
AddHeaders(ref request, authToken);
var account = RetryHandler.Execute<PlexAccount>(() => Api.ExecuteXml<PlexAccount> (request, new Uri(GetAccountUri)),
null,
(exception, timespan) => Log.Error (exception, "Exception when calling GetAccount for Plex, Retrying {0}", timespan));
return account;
}
public PlexLibraries GetLibrarySections(string authToken, Uri plexFullHost)
{
var request = new RestRequest
{
Method = Method.GET,
Resource = "library/sections"
};
AddHeaders(ref request, authToken);
try
{
var lib = RetryHandler.Execute<PlexLibraries>(() => Api.ExecuteXml<PlexLibraries> (request, plexFullHost),
new TimeSpan[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
},
(exception, timespan) => Log.Error (exception, "Exception when calling GetLibrarySections for Plex, Retrying {0}", timespan));
return lib;
}
catch (Exception e)
{
Log.Error(e,"There has been a API Exception when attempting to get the Plex Libraries");
return new PlexLibraries();
}
}
public PlexSearch GetLibrary(string authToken, Uri plexFullHost, string libraryId)
{
var request = new RestRequest
{
Method = Method.GET,
Resource = "library/sections/{libraryId}/all"
};
request.AddUrlSegment("libraryId", libraryId);
AddHeaders(ref request, authToken);
try
{
var lib = RetryHandler.Execute<PlexSearch>(() => Api.ExecuteXml<PlexSearch> (request, plexFullHost),
new TimeSpan[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
},
(exception, timespan) => Log.Error (exception, "Exception when calling GetLibrary for Plex, Retrying {0}", timespan));
return lib;
}
catch (Exception e)
{
Log.Error(e,"There has been a API Exception when attempting to get the Plex Library");
return new PlexSearch();
}
}
public PlexMetadata GetMetadata(string authToken, Uri plexFullHost, string itemId)
{
var request = new RestRequest
{
Method = Method.GET,
Resource = "library/metadata/{itemId}"
};
request.AddUrlSegment("itemId", itemId);
AddHeaders(ref request, authToken);
try
{
var lib = RetryHandler.Execute(() => Api.ExecuteXml<PlexMetadata>(request, plexFullHost),
new[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
},
(exception, timespan) => Log.Error(exception, "Exception when calling GetMetadata for Plex, Retrying {0}", timespan));
return lib;
}
catch (Exception e)
{
Log.Error(e, "There has been a API Exception when attempting to get the Plex GetMetadata");
return new PlexMetadata();
}
}
private void AddHeaders(ref RestRequest request, string authToken)
{
request.AddHeader("X-Plex-Token", authToken);
AddHeaders(ref request);
}
private void AddHeaders(ref RestRequest request)
{
request.AddHeader("X-Plex-Client-Identifier", "Test213");
request.AddHeader("X-Plex-Product", "Request Plex");
request.AddHeader("X-Plex-Version", Version);
request.AddHeader("Content-Type", "application/xml");
}
}
}
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: PlexApi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
using Polly;
#endregion
using System;
using NLog;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Plex;
using PlexRequests.Helpers;
using PlexRequests.Helpers.Exceptions;
using RestSharp;
namespace PlexRequests.Api
{
public class PlexApi : IPlexApi
{
static PlexApi()
{
Version = AssemblyHelper.GetAssemblyVersion();
}
public PlexApi (IApiRequest api)
{
Api = api;
}
private IApiRequest Api { get; }
private const string SignInUri = "https://plex.tv/users/sign_in.json";
private const string FriendsUri = "https://plex.tv/pms/friends/all";
private const string GetAccountUri = "https://plex.tv/users/account";
private static Logger Log = LogManager.GetCurrentClassLogger();
private static string Version { get; }
public PlexAuthentication SignIn(string username, string password)
{
var userModel = new PlexUserRequest
{
user = new UserRequest
{
password = password,
login = username
}
};
var request = new RestRequest
{
Method = Method.POST
};
AddHeaders(ref request);
request.AddJsonBody(userModel);
var obj = RetryHandler.Execute<PlexAuthentication>(() => Api.Execute<PlexAuthentication> (request, new Uri(SignInUri)),
(exception, timespan) => Log.Error (exception, "Exception when calling SignIn for Plex, Retrying {0}", timespan), null);
return obj;
}
public PlexFriends GetUsers(string authToken)
{
var request = new RestRequest
{
Method = Method.GET,
};
AddHeaders(ref request, authToken);
var users = RetryHandler.Execute(() => Api.ExecuteXml<PlexFriends> (request, new Uri(FriendsUri)),
(exception, timespan) => Log.Error (exception, "Exception when calling GetUsers for Plex, Retrying {0}", timespan), null);
return users;
}
/// <summary>
/// Gets the users.
/// </summary>
/// <param name="authToken">The authentication token.</param>
/// <param name="searchTerm">The search term.</param>
/// <param name="plexFullHost">The full plex host.</param>
/// <returns></returns>
public PlexSearch SearchContent(string authToken, string searchTerm, Uri plexFullHost)
{
var request = new RestRequest
{
Method = Method.GET,
Resource = "search?query={searchTerm}"
};
request.AddUrlSegment("searchTerm", searchTerm);
AddHeaders(ref request, authToken);
var search = RetryHandler.Execute<PlexSearch>(() => Api.ExecuteXml<PlexSearch> (request, plexFullHost),
(exception, timespan) => Log.Error (exception, "Exception when calling SearchContent for Plex, Retrying {0}", timespan), null);
return search;
}
public PlexStatus GetStatus(string authToken, Uri uri)
{
var request = new RestRequest
{
Method = Method.GET,
};
AddHeaders(ref request, authToken);
var users = RetryHandler.Execute<PlexStatus>(() => Api.ExecuteXml<PlexStatus> (request, uri),
(exception, timespan) => Log.Error (exception, "Exception when calling GetStatus for Plex, Retrying {0}", timespan), null);
return users;
}
public PlexAccount GetAccount(string authToken)
{
var request = new RestRequest
{
Method = Method.GET,
};
AddHeaders(ref request, authToken);
var account = RetryHandler.Execute<PlexAccount>(() => Api.ExecuteXml<PlexAccount> (request, new Uri(GetAccountUri)),
(exception, timespan) => Log.Error (exception, "Exception when calling GetAccount for Plex, Retrying {0}", timespan), null);
return account;
}
public PlexLibraries GetLibrarySections(string authToken, Uri plexFullHost)
{
var request = new RestRequest
{
Method = Method.GET,
Resource = "library/sections"
};
AddHeaders(ref request, authToken);
try
{
var lib = RetryHandler.Execute<PlexLibraries>(() => Api.ExecuteXml<PlexLibraries> (request, plexFullHost),
(exception, timespan) => Log.Error (exception, "Exception when calling GetLibrarySections for Plex, Retrying {0}", timespan), new TimeSpan[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
});
return lib;
}
catch (Exception e)
{
Log.Error(e,"There has been a API Exception when attempting to get the Plex Libraries");
return new PlexLibraries();
}
}
public PlexSearch GetLibrary(string authToken, Uri plexFullHost, string libraryId)
{
var request = new RestRequest
{
Method = Method.GET,
Resource = "library/sections/{libraryId}/all"
};
request.AddUrlSegment("libraryId", libraryId);
AddHeaders(ref request, authToken);
try
{
var lib = RetryHandler.Execute<PlexSearch>(() => Api.ExecuteXml<PlexSearch> (request, plexFullHost),
(exception, timespan) => Log.Error (exception, "Exception when calling GetLibrary for Plex, Retrying {0}", timespan), new TimeSpan[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
});
return lib;
}
catch (Exception e)
{
Log.Error(e,"There has been a API Exception when attempting to get the Plex Library");
return new PlexSearch();
}
}
public PlexMetadata GetMetadata(string authToken, Uri plexFullHost, string itemId)
{
var request = new RestRequest
{
Method = Method.GET,
Resource = "library/metadata/{itemId}"
};
request.AddUrlSegment("itemId", itemId);
AddHeaders(ref request, authToken);
try
{
var lib = RetryHandler.Execute(() => Api.ExecuteXml<PlexMetadata>(request, plexFullHost),
(exception, timespan) => Log.Error(exception, "Exception when calling GetMetadata for Plex, Retrying {0}", timespan), new[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
});
return lib;
}
catch (Exception e)
{
Log.Error(e, "There has been a API Exception when attempting to get the Plex GetMetadata");
return new PlexMetadata();
}
}
private void AddHeaders(ref RestRequest request, string authToken)
{
request.AddHeader("X-Plex-Token", authToken);
AddHeaders(ref request);
}
private void AddHeaders(ref RestRequest request)
{
request.AddHeader("X-Plex-Client-Identifier", "Test213");
request.AddHeader("X-Plex-Product", "Request Plex");
request.AddHeader("X-Plex-Version", Version);
request.AddHeader("Content-Type", "application/xml");
}
}
}

View file

@ -35,25 +35,29 @@ namespace PlexRequests.Api
{
private static readonly TimeSpan[] DefaultTime = { TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10) };
public static T Execute<T>(Func<T> action, TimeSpan[] timeSpan)
{
var policy = RetryAndWaitPolicy(timeSpan);
return policy.Execute(action);
}
public static T Execute<T>(Func<T> func, TimeSpan[] timeSpan, Action<Exception, TimeSpan> action)
public static T Execute<T>(Func<T> action, TimeSpan[] timeSpan = null)
{
if (timeSpan == null)
{
timeSpan = DefaultTime;
}
var policy = RetryAndWaitPolicy(timeSpan, action);
var policy = RetryAndWaitPolicy(timeSpan);
return policy.Execute(action);
}
public static T Execute<T>(Func<T> func, Action<Exception, TimeSpan> action, TimeSpan[] timeSpan = null)
{
if (timeSpan == null)
{
timeSpan = DefaultTime;
}
var policy = RetryAndWaitPolicy(action, timeSpan);
return policy.Execute(func);
}
public static RetryPolicy RetryAndWaitPolicy(TimeSpan[] timeSpan, Action action)
public static RetryPolicy RetryAndWaitPolicy(Action action, TimeSpan[] timeSpan = null)
{
if (timeSpan == null)
{
@ -75,7 +79,7 @@ namespace PlexRequests.Api
return policy;
}
public static RetryPolicy RetryAndWaitPolicy(TimeSpan[] timeSpan, Action<Exception, TimeSpan> action)
public static RetryPolicy RetryAndWaitPolicy(Action<Exception, TimeSpan> action, TimeSpan[] timeSpan = null)
{
if (timeSpan == null)
{

View file

@ -1,227 +1,217 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: SickrageApi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System.Linq;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using NLog;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.SickRage;
using PlexRequests.Helpers;
using PlexRequests.Helpers.Exceptions;
using RestSharp;
namespace PlexRequests.Api
{
public class SickrageApi : ISickRageApi
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
public SickrageApi()
{
Api = new ApiRequest();
}
private ApiRequest Api { get; }
public SickRageSeasonList VerifyShowHasLoaded(int tvdbId, string apiKey, Uri baseUrl)
{
Log.Trace("Entered `VerifyShowHasLoaded({0} <- id)`", tvdbId);
var request = new RestRequest { Resource = "/api/{apiKey}/?cmd=show.seasonlist", Method = Method.GET };
request.AddUrlSegment("apiKey", apiKey);
request.AddQueryParameter("tvdbid", tvdbId.ToString());
try
{
var policy = RetryHandler.RetryAndWaitPolicy(
null,
(exception, timespan) => Log.Error(exception, "Exception when calling VerifyShowHasLoaded for SR, Retrying {0}", timespan));
var obj = policy.Execute(() => Api.ExecuteJson<SickRageSeasonList>(request, baseUrl));
return obj;
}
catch (Exception e)
{
Log.Error(e);
return new SickRageSeasonList();
}
}
public async Task<SickRageTvAdd> AddSeries(int tvdbId, int seasonCount, int[] seasons, string quality, string apiKey, Uri baseUrl)
{
var futureStatus = seasons.Length > 0 && !seasons.Any(x => x == seasonCount) ? SickRageStatus.Skipped : SickRageStatus.Wanted;
var status = seasons.Length > 0 ? SickRageStatus.Skipped : SickRageStatus.Wanted;
Log.Trace("Future Status: {0}", futureStatus);
Log.Trace("Current Status: {0}", status);
var request = new RestRequest { Resource = "/api/{apiKey}/?cmd=show.addnew", Method = Method.GET };
request.AddUrlSegment("apiKey", apiKey);
request.AddQueryParameter("tvdbid", tvdbId.ToString());
request.AddQueryParameter("status", status);
request.AddQueryParameter("future_status", futureStatus);
if (!quality.Equals("default", StringComparison.CurrentCultureIgnoreCase))
{
Log.Trace("Settings quality to {0}", quality);
request.AddQueryParameter("initial", quality);
}
var policy = RetryHandler.RetryAndWaitPolicy(
null,
(exception, timespan) => Log.Error(exception, "Exception when calling AddSeries for SR, Retrying {0}", timespan));
var obj = policy.Execute(() => Api.Execute<SickRageTvAdd>(request, baseUrl));
Log.Trace("obj Result:");
Log.Trace(obj.DumpJson());
if (obj.result != "failure")
{
var sw = new Stopwatch();
sw.Start();
var seasonIncrement = 0;
var seasonList = new SickRageSeasonList();
try
{
while (seasonIncrement < seasonCount)
{
seasonList = VerifyShowHasLoaded(tvdbId, apiKey, baseUrl);
if (seasonList.result.Equals("failure"))
{
Thread.Sleep(3000);
continue;
}
seasonIncrement = seasonList.Data?.Length ?? 0;
Log.Trace("New seasonIncrement -> {0}", seasonIncrement);
if (sw.ElapsedMilliseconds > 30000) // Break out after 30 seconds, it's not going to get added
{
Log.Warn("Couldn't find out if the show had been added after 10 seconds. I doubt we can change the status to wanted.");
break;
}
}
sw.Stop();
}
catch (Exception e)
{
Log.Error("Exception thrown when getting the seasonList");
Log.Error(e);
}
}
Log.Trace("seasons.Length > 0 where seasons.Len -> {0}", seasons.Length);
try
{
if (seasons.Length > 0)
{
//handle the seasons requested
foreach (var s in seasons)
{
Log.Trace("Adding season {0}", s);
var result = await AddSeason(tvdbId, s, apiKey, baseUrl);
Log.Trace("SickRage adding season results: ");
Log.Trace(result.DumpJson());
}
}
}
catch (Exception e)
{
Log.Trace("Exception when adding seasons:");
Log.Error(e);
throw;
}
Log.Trace("Finished with the API, returning the obj");
return obj;
}
public SickRagePing Ping(string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/{apiKey}/?cmd=sb.ping", Method = Method.GET };
var policy = RetryHandler.RetryAndWaitPolicy(
null,
(exception, timespan) => Log.Error(exception, "Exception when calling Ping for SR, Retrying {0}", timespan));
request.AddUrlSegment("apiKey", apiKey);
var obj = policy.Execute(() => Api.ExecuteJson<SickRagePing>(request, baseUrl));
return obj;
}
public async Task<SickRageTvAdd> AddSeason(int tvdbId, int season, string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/{apiKey}/?cmd=episode.setstatus", Method = Method.GET };
request.AddUrlSegment("apiKey", apiKey);
request.AddQueryParameter("tvdbid", tvdbId.ToString());
request.AddQueryParameter("season", season.ToString());
request.AddQueryParameter("status", SickRageStatus.Wanted);
await Task.Run(() => Thread.Sleep(2000));
return await Task.Run(
() =>
{
var policy = RetryHandler.RetryAndWaitPolicy(
null,
(exception, timespan) => Log.Error(exception, "Exception when calling AddSeason for SR, Retrying {0}", timespan));
var result = policy.Execute(() => Api.Execute<SickRageTvAdd>(request, baseUrl));
return result;
}).ConfigureAwait(false);
}
public async Task<SickrageShows> GetShows(string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/{apiKey}/?cmd=shows", Method = Method.GET };
request.AddUrlSegment("apiKey", apiKey);
return await Task.Run(
() =>
{
try
{
var policy = RetryHandler.RetryAndWaitPolicy(
new[] { TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) },
(exception, timespan) => Log.Error(exception, "Exception when calling GetShows for SR, Retrying {0}", timespan));
return policy.Execute(() => Api.Execute<SickrageShows>(request, baseUrl));
}
catch (ApiRequestException)
{
Log.Error("There has been a API exception when Getting the Sickrage shows");
return null;
}
}).ConfigureAwait(false);
}
}
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: SickrageApi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System.Linq;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using NLog;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.SickRage;
using PlexRequests.Helpers;
using PlexRequests.Helpers.Exceptions;
using RestSharp;
namespace PlexRequests.Api
{
public class SickrageApi : ISickRageApi
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
public SickrageApi()
{
Api = new ApiRequest();
}
private ApiRequest Api { get; }
public SickRageSeasonList VerifyShowHasLoaded(int tvdbId, string apiKey, Uri baseUrl)
{
Log.Trace("Entered `VerifyShowHasLoaded({0} <- id)`", tvdbId);
var request = new RestRequest { Resource = "/api/{apiKey}/?cmd=show.seasonlist", Method = Method.GET };
request.AddUrlSegment("apiKey", apiKey);
request.AddQueryParameter("tvdbid", tvdbId.ToString());
try
{
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) => Log.Error(exception, "Exception when calling VerifyShowHasLoaded for SR, Retrying {0}", timespan), null);
var obj = policy.Execute(() => Api.ExecuteJson<SickRageSeasonList>(request, baseUrl));
return obj;
}
catch (Exception e)
{
Log.Error(e);
return new SickRageSeasonList();
}
}
public async Task<SickRageTvAdd> AddSeries(int tvdbId, int seasonCount, int[] seasons, string quality, string apiKey, Uri baseUrl)
{
var futureStatus = seasons.Length > 0 && !seasons.Any(x => x == seasonCount) ? SickRageStatus.Skipped : SickRageStatus.Wanted;
var status = seasons.Length > 0 ? SickRageStatus.Skipped : SickRageStatus.Wanted;
Log.Trace("Future Status: {0}", futureStatus);
Log.Trace("Current Status: {0}", status);
var request = new RestRequest { Resource = "/api/{apiKey}/?cmd=show.addnew", Method = Method.GET };
request.AddUrlSegment("apiKey", apiKey);
request.AddQueryParameter("tvdbid", tvdbId.ToString());
request.AddQueryParameter("status", status);
request.AddQueryParameter("future_status", futureStatus);
if (!quality.Equals("default", StringComparison.CurrentCultureIgnoreCase))
{
Log.Trace("Settings quality to {0}", quality);
request.AddQueryParameter("initial", quality);
}
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) => Log.Error(exception, "Exception when calling AddSeries for SR, Retrying {0}", timespan), null);
var obj = policy.Execute(() => Api.Execute<SickRageTvAdd>(request, baseUrl));
Log.Trace("obj Result:");
Log.Trace(obj.DumpJson());
if (obj.result != "failure")
{
var sw = new Stopwatch();
sw.Start();
var seasonIncrement = 0;
var seasonList = new SickRageSeasonList();
try
{
while (seasonIncrement < seasonCount)
{
seasonList = VerifyShowHasLoaded(tvdbId, apiKey, baseUrl);
if (seasonList.result.Equals("failure"))
{
Thread.Sleep(3000);
continue;
}
seasonIncrement = seasonList.Data?.Length ?? 0;
Log.Trace("New seasonIncrement -> {0}", seasonIncrement);
if (sw.ElapsedMilliseconds > 30000) // Break out after 30 seconds, it's not going to get added
{
Log.Warn("Couldn't find out if the show had been added after 10 seconds. I doubt we can change the status to wanted.");
break;
}
}
sw.Stop();
}
catch (Exception e)
{
Log.Error("Exception thrown when getting the seasonList");
Log.Error(e);
}
}
Log.Trace("seasons.Length > 0 where seasons.Len -> {0}", seasons.Length);
try
{
if (seasons.Length > 0)
{
//handle the seasons requested
foreach (var s in seasons)
{
Log.Trace("Adding season {0}", s);
var result = await AddSeason(tvdbId, s, apiKey, baseUrl);
Log.Trace("SickRage adding season results: ");
Log.Trace(result.DumpJson());
}
}
}
catch (Exception e)
{
Log.Trace("Exception when adding seasons:");
Log.Error(e);
throw;
}
Log.Trace("Finished with the API, returning the obj");
return obj;
}
public SickRagePing Ping(string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/{apiKey}/?cmd=sb.ping", Method = Method.GET };
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) => Log.Error(exception, "Exception when calling Ping for SR, Retrying {0}", timespan), null);
request.AddUrlSegment("apiKey", apiKey);
var obj = policy.Execute(() => Api.ExecuteJson<SickRagePing>(request, baseUrl));
return obj;
}
public async Task<SickRageTvAdd> AddSeason(int tvdbId, int season, string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/{apiKey}/?cmd=episode.setstatus", Method = Method.GET };
request.AddUrlSegment("apiKey", apiKey);
request.AddQueryParameter("tvdbid", tvdbId.ToString());
request.AddQueryParameter("season", season.ToString());
request.AddQueryParameter("status", SickRageStatus.Wanted);
await Task.Run(() => Thread.Sleep(2000));
return await Task.Run(
() =>
{
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) => Log.Error(exception, "Exception when calling AddSeason for SR, Retrying {0}", timespan), null);
var result = policy.Execute(() => Api.Execute<SickRageTvAdd>(request, baseUrl));
return result;
}).ConfigureAwait(false);
}
public async Task<SickrageShows> GetShows(string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/{apiKey}/?cmd=shows", Method = Method.GET };
request.AddUrlSegment("apiKey", apiKey);
return await Task.Run(
() =>
{
try
{
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) => Log.Error(exception, "Exception when calling GetShows for SR, Retrying {0}", timespan), new[] { TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) });
return policy.Execute(() => Api.Execute<SickrageShows>(request, baseUrl));
}
catch (ApiRequestException)
{
Log.Error("There has been a API exception when Getting the Sickrage shows");
return null;
}
}).ConfigureAwait(false);
}
}
}

View file

@ -1,167 +1,299 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: CouchPotatoApi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using NLog;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Sonarr;
using PlexRequests.Helpers;
using RestSharp;
using Newtonsoft.Json.Linq;
using PlexRequests.Helpers.Exceptions;
namespace PlexRequests.Api
{
public class SonarrApi : ISonarrApi
{
public SonarrApi()
{
Api = new ApiRequest();
}
private ApiRequest Api { get; set; }
private static Logger Log = LogManager.GetCurrentClassLogger();
public List<SonarrProfile> GetProfiles(string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/profile", Method = Method.GET };
request.AddHeader("X-Api-Key", apiKey);
var policy = RetryHandler.RetryAndWaitPolicy (new TimeSpan[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
}, (exception, timespan) => Log.Error (exception, "Exception when calling GetProfiles for Sonarr, Retrying {0}", timespan));
var obj = policy.Execute(() => Api.ExecuteJson<List<SonarrProfile>>(request, baseUrl));
return obj;
}
public SonarrAddSeries AddSeries(int tvdbId, string title, int qualityId, bool seasonFolders, string rootPath, int seasonCount, int[] seasons, string apiKey, Uri baseUrl)
{
Log.Debug("Adding series {0}", title);
Log.Debug("Seasons = {0}, out of {1} seasons", seasons.DumpJson(), seasonCount);
var request = new RestRequest
{
Resource = "/api/Series?",
Method = Method.POST
};
var options = new SonarrAddSeries
{
seasonFolder = seasonFolders,
title = title,
qualityProfileId = qualityId,
tvdbId = tvdbId,
titleSlug = title,
seasons = new List<Season>(),
rootFolderPath = rootPath
};
for (var i = 1; i <= seasonCount; i++)
{
var season = new Season
{
seasonNumber = i,
monitored = seasons.Length == 0 || seasons.Any(x => x == i)
};
options.seasons.Add(season);
}
Log.Debug("Sonarr API Options:");
Log.Debug(options.DumpJson());
request.AddHeader("X-Api-Key", apiKey);
request.AddJsonBody(options);
SonarrAddSeries result;
try
{
var policy = RetryHandler.RetryAndWaitPolicy (new TimeSpan[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
}, (exception, timespan) => Log.Error (exception, "Exception when calling AddSeries for Sonarr, Retrying {0}", timespan));
result = policy.Execute(() => Api.ExecuteJson<SonarrAddSeries>(request, baseUrl));
}
catch (JsonSerializationException jse)
{
Log.Error(jse);
var error = Api.ExecuteJson<List<SonarrError>>(request, baseUrl);
var messages = error?.Select(x => x.errorMessage).ToList();
messages?.ForEach(x => Log.Error(x));
result = new SonarrAddSeries { ErrorMessages = messages };
}
return result;
}
public SystemStatus SystemStatus(string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/system/status", Method = Method.GET };
request.AddHeader("X-Api-Key", apiKey);
var policy = RetryHandler.RetryAndWaitPolicy (new TimeSpan[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
}, (exception, timespan) => Log.Error (exception, "Exception when calling SystemStatus for Sonarr, Retrying {0}", timespan));
var obj = policy.Execute(() => Api.ExecuteJson<SystemStatus>(request, baseUrl));
return obj;
}
public List<Series> GetSeries(string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/series", Method = Method.GET };
request.AddHeader("X-Api-Key", apiKey);
try
{
var policy = RetryHandler.RetryAndWaitPolicy (new TimeSpan[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
}, (exception, timespan) => Log.Error (exception, "Exception when calling GetSeries for Sonarr, Retrying {0}", timespan));
return policy.Execute(() => Api.ExecuteJson<List<Series>>(request, baseUrl));
}
catch (Exception e)
{
Log.Error(e, "There has been an API exception when getting the Sonarr Series");
return null;
}
}
}
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: CouchPotatoApi.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using NLog;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Sonarr;
using PlexRequests.Helpers;
using RestSharp;
namespace PlexRequests.Api
{
public class SonarrApi : ISonarrApi
{
public SonarrApi()
{
Api = new ApiRequest();
}
private ApiRequest Api { get; set; }
private static Logger Log = LogManager.GetCurrentClassLogger();
public List<SonarrProfile> GetProfiles(string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/profile", Method = Method.GET };
request.AddHeader("X-Api-Key", apiKey);
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) => Log.Error(exception, "Exception when calling GetProfiles for Sonarr, Retrying {0}", timespan), new TimeSpan[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
});
var obj = policy.Execute(() => Api.ExecuteJson<List<SonarrProfile>>(request, baseUrl));
return obj;
}
public SonarrAddSeries AddSeries(int tvdbId, string title, int qualityId, bool seasonFolders, string rootPath, int seasonCount, int[] seasons, string apiKey, Uri baseUrl)
{
Log.Debug("Adding series {0}", title);
Log.Debug("Seasons = {0}, out of {1} seasons", seasons.DumpJson(), seasonCount);
var request = new RestRequest
{
Resource = "/api/Series?",
Method = Method.POST
};
var options = new SonarrAddSeries
{
seasonFolder = seasonFolders,
title = title,
qualityProfileId = qualityId,
tvdbId = tvdbId,
titleSlug = title,
seasons = new List<Season>(),
rootFolderPath = rootPath
};
for (var i = 1; i <= seasonCount; i++)
{
var season = new Season
{
seasonNumber = i,
monitored = seasons.Length == 0 || seasons.Any(x => x == i)
};
options.seasons.Add(season);
}
Log.Debug("Sonarr API Options:");
Log.Debug(options.DumpJson());
request.AddHeader("X-Api-Key", apiKey);
request.AddJsonBody(options);
SonarrAddSeries result;
try
{
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) => Log.Error(exception, "Exception when calling AddSeries for Sonarr, Retrying {0}", timespan), new TimeSpan[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
});
result = policy.Execute(() => Api.ExecuteJson<SonarrAddSeries>(request, baseUrl));
}
catch (JsonSerializationException jse)
{
Log.Error(jse);
var error = Api.ExecuteJson<List<SonarrError>>(request, baseUrl);
var messages = error?.Select(x => x.errorMessage).ToList();
messages?.ForEach(x => Log.Error(x));
result = new SonarrAddSeries { ErrorMessages = messages };
}
return result;
}
public SystemStatus SystemStatus(string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/system/status", Method = Method.GET };
request.AddHeader("X-Api-Key", apiKey);
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) => Log.Error(exception, "Exception when calling SystemStatus for Sonarr, Retrying {0}", timespan), new TimeSpan[] {
TimeSpan.FromSeconds (2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
});
var obj = policy.Execute(() => Api.ExecuteJson<SystemStatus>(request, baseUrl));
return obj;
}
public List<Series> GetSeries(string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/series", Method = Method.GET };
request.AddHeader("X-Api-Key", apiKey);
try
{
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) => Log.Error(exception, "Exception when calling GetSeries for Sonarr, Retrying {0}", timespan), new TimeSpan[] {
TimeSpan.FromSeconds (5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
});
return policy.Execute(() => Api.ExecuteJson<List<Series>>(request, baseUrl));
}
catch (Exception e)
{
Log.Error(e, "There has been an API exception when getting the Sonarr Series");
return null;
}
}
public Series GetSeries(string seriesId, string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/series/{seriesId}", Method = Method.GET };
request.AddHeader("X-Api-Key", apiKey);
request.AddUrlSegment("seriesId", seriesId);
try
{
var policy =
RetryHandler.RetryAndWaitPolicy(
(exception, timespan) =>
Log.Error(exception, "Exception when calling GetSeries by ID for Sonarr, Retrying {0}",
timespan));
return policy.Execute(() => Api.ExecuteJson<Series>(request, baseUrl));
}
catch (Exception e)
{
Log.Error(e, "There has been an API exception when getting the Sonarr Series by ID");
return null;
}
}
/// <summary>
/// Returns all episodes for the given series.
/// </summary>
/// <param name="seriesId">The series identifier.</param>
/// <param name="apiKey">The API key.</param>
/// <param name="baseUrl">The base URL.</param>
/// <returns></returns>
public IEnumerable<SonarrEpisodes> GetEpisodes(string seriesId, string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/Episode", Method = Method.GET };
request.AddHeader("X-Api-Key", apiKey);
request.AddQueryParameter("seriesId", seriesId);
try
{
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) =>
Log.Error(exception, "Exception when calling GetEpisodes for Sonarr, Retrying {0}", timespan));
return policy.Execute(() => Api.ExecuteJson<List<SonarrEpisodes>>(request, baseUrl));
}
catch (Exception e)
{
Log.Error(e, "There has been an API exception when getting the Sonarr GetEpisodes");
return null;
}
}
/// <summary>
/// Returns the episode with the matching id.
/// </summary>
/// <param name="episodeId">The episode identifier.</param>
/// <param name="apiKey">The API key.</param>
/// <param name="baseUrl">The base URL.</param>
/// <returns></returns>
public SonarrEpisode GetEpisode(string episodeId, string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/Episode/{episodeId}", Method = Method.GET };
request.AddHeader("X-Api-Key", apiKey);
request.AddUrlSegment("episodeId", episodeId);
try
{
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) =>
Log.Error(exception, "Exception when calling GetEpisode by ID for Sonarr, Retrying {0}", timespan));
return policy.Execute(() => Api.ExecuteJson<SonarrEpisode>(request, baseUrl));
}
catch (Exception e)
{
Log.Error(e, "There has been an API exception when getting the Sonarr GetEpisode by ID");
return null;
}
}
/// <summary>
/// Update the given episodes, currently only monitored is changed, all other modifications are ignored.
/// Required: All parameters (you should perform a GET/{id} and submit the full body with the changes, as other values may be editable in the future.
/// </summary>
/// <param name="episodeInfo">The episode information.</param>
/// <param name="apiKey">The API key.</param>
/// <param name="baseUrl">The base URL.</param>
/// <returns></returns>
public SonarrEpisode UpdateEpisode(SonarrEpisode episodeInfo, string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/Episode", Method = Method.PUT };
request.AddHeader("X-Api-Key", apiKey);
request.AddJsonBody(episodeInfo);
try
{
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) =>
Log.Error(exception, "Exception when calling UpdateEpisode for Sonarr, Retrying {0}", timespan));
return policy.Execute(() => Api.ExecuteJson<SonarrEpisode>(request, baseUrl));
}
catch (Exception e)
{
Log.Error(e, "There has been an API exception when put the Sonarr UpdateEpisode");
return null;
}
}
/// <summary>
/// Search for one or more episodes
/// </summary>
/// <param name="episodeIds">The episode ids.</param>
/// <param name="apiKey">The API key.</param>
/// <param name="baseUrl">The base URL.</param>
/// <returns></returns>
public SonarrAddEpisodeResult SearchForEpisodes(int[] episodeIds, string apiKey, Uri baseUrl)
{
var request = new RestRequest { Resource = "/api/Command", Method = Method.POST };
request.AddHeader("X-Api-Key", apiKey);
var body = new SonarrAddEpisodeBody
{
name = "EpisodeSearch",
episodeIds = episodeIds
};
request.AddJsonBody(body);
try
{
var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) =>
Log.Error(exception, "Exception when calling SearchForEpisodes for Sonarr, Retrying {0}", timespan));
return policy.Execute(() => Api.ExecuteJson<SonarrAddEpisodeResult>(request, baseUrl));
}
catch (Exception e)
{
Log.Error(e, "There has been an API exception when put the Sonarr SearchForEpisodes");
return null;
}
}
}
}