Lots of fixed and stuff.

pull/687/head
Jamie.Rees 8 years ago
parent cb3c3fe10e
commit 7412655c5a

@ -104,8 +104,7 @@ namespace PlexRequests.Api
}
var result = DeserializeXml<T>(response.Content);
return result;
}
return result;}
public T ExecuteJson<T>(IRestRequest request, Uri baseUri) where T : new()
{

@ -145,26 +145,6 @@ namespace PlexRequests.Core
Repo.Delete(user);
}
public Guid? CreateAdmin(string username, string password, UserProperties properties = null)
{
return CreateUser(username, password, properties);
}
public Guid? CreatePowerUser(string username, string password, UserProperties properties = null)
{
return CreateUser(username, password, properties);
}
public Guid? CreateRegularUser(string username, string password, UserProperties properties = null)
{
return CreateUser(username, password, properties);
}
public IEnumerable<string> GetAllClaims()
{
var properties = typeof(UserClaims).GetConstantsValues<string>();
return properties;
}
public bool UpdatePassword(string username, string oldPassword, string newPassword)
{
@ -207,11 +187,8 @@ namespace PlexRequests.Core
public interface ICustomUserMapper
{
Guid? CreateUser(string username, string password, UserProperties props);
Guid? CreateUser(string username, string password, int permissions, int features,
UserProperties properties = null);
IEnumerable<string> GetAllClaims();
IEnumerable<UsersModel> GetUsers();
Task<IEnumerable<UsersModel>> GetUsersAsync();
UsersModel GetUser(Guid userId);
@ -219,9 +196,6 @@ namespace PlexRequests.Core
bool DoUsersExist();
Guid? ValidateUser(string username, string password);
bool UpdatePassword(string username, string oldPassword, string newPassword);
Guid? CreateAdmin(string username, string password, UserProperties properties = null);
Guid? CreatePowerUser(string username, string password, UserProperties properties = null);
Guid? CreateRegularUser(string username, string password, UserProperties properties = null);
void DeleteUser(string userId);
}
}

@ -108,5 +108,10 @@ namespace PlexRequests.Helpers
throw new ArgumentOutOfRangeException(nameof(name));
}
public static int All()
{
return Enum.GetValues(typeof(T)).Cast<int>().Sum();
}
}
}

@ -59,6 +59,5 @@ namespace PlexRequests.Helpers.Permissions
[Display(Name = "Auto Approve Album Requests")]
AutoApproveAlbum = 256
}
}

@ -1,284 +1,284 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: PlexAvailabilityCheckerTests.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.Data;
using System.Linq;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Plex;
using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
using PlexRequests.Services.Interfaces;
using PlexRequests.Helpers;
using PlexRequests.Services.Jobs;
using PlexRequests.Services.Models;
using PlexRequests.Services.Notification;
using PlexRequests.Store.Models;
using PlexRequests.Store.Repository;
using Ploeh.AutoFixture;
namespace PlexRequests.Services.Tests
{
[TestFixture]
public class PlexAvailabilityCheckerTests
{
public IAvailabilityChecker Checker { get; set; }
private Fixture F { get; set; } = new Fixture();
private Mock<ISettingsService<PlexSettings>> SettingsMock { get; set; }
private Mock<ISettingsService<AuthenticationSettings>> AuthMock { get; set; }
private Mock<IRequestService> RequestMock { get; set; }
private Mock<IPlexApi> PlexMock { get; set; }
private Mock<ICacheProvider> CacheMock { get; set; }
private Mock<INotificationService> NotificationMock { get; set; }
private Mock<IJobRecord> JobRec { get; set; }
private Mock<IRepository<UsersToNotify>> NotifyUsers { get; set; }
private Mock<IRepository<PlexEpisodes>> PlexEpisodes { get; set; }
private Mock<INotificationEngine> Engine
{
get;
set;
}
[SetUp]
public void Setup()
{
SettingsMock = new Mock<ISettingsService<PlexSettings>>();
AuthMock = new Mock<ISettingsService<AuthenticationSettings>>();
RequestMock = new Mock<IRequestService>();
PlexMock = new Mock<IPlexApi>();
NotificationMock = new Mock<INotificationService>();
CacheMock = new Mock<ICacheProvider>();
NotifyUsers = new Mock<IRepository<UsersToNotify>>();
PlexEpisodes = new Mock<IRepository<PlexEpisodes>>();
JobRec = new Mock<IJobRecord>();
Engine = new Mock<INotificationEngine>();
Checker = new PlexAvailabilityChecker(SettingsMock.Object, RequestMock.Object, PlexMock.Object, CacheMock.Object, NotificationMock.Object, JobRec.Object, NotifyUsers.Object, PlexEpisodes.Object, Engine.Object);
}
[Test]
public void InvalidSettings()
{
Checker.CheckAndUpdateAll();
PlexMock.Verify(x => x.GetLibrary(It.IsAny<string>(), It.IsAny<Uri>(), It.IsAny<string>()), Times.Never);
PlexMock.Verify(x => x.GetAccount(It.IsAny<string>()), Times.Never);
PlexMock.Verify(x => x.GetLibrarySections(It.IsAny<string>(), It.IsAny<Uri>()), Times.Never);
PlexMock.Verify(x => x.GetStatus(It.IsAny<string>(), It.IsAny<Uri>()), Times.Never);
PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never);
}
[TestCaseSource(nameof(IsMovieAvailableTestData))]
public bool IsMovieAvailableTest(string title, string year)
{
var movies = new List<PlexMovie>
{
new PlexMovie {Title = title, ProviderId = null, ReleaseYear = year}
};
var result = Checker.IsMovieAvailable(movies.ToArray(), "title", "2011");
return result;
}
private static IEnumerable<TestCaseData> IsMovieAvailableTestData
{
get
{
yield return new TestCaseData("title", "2011").Returns(true).SetName("IsMovieAvailable True");
yield return new TestCaseData("title2", "2011").Returns(false).SetName("IsMovieAvailable False different title");
yield return new TestCaseData("title", "2001").Returns(false).SetName("IsMovieAvailable False different year");
}
}
[TestCaseSource(nameof(IsMovieAvailableAdvancedTestData))]
public bool IsMovieAvailableAdvancedTest(string title, string year, string providerId)
{
var movies = new List<PlexMovie>
{
new PlexMovie {Title = title, ProviderId = providerId, ReleaseYear = year }
};
var result = Checker.IsMovieAvailable(movies.ToArray(), "title", "2011", 9999.ToString());
return result;
}
private static IEnumerable<TestCaseData> IsMovieAvailableAdvancedTestData
{
get
{
yield return new TestCaseData("title", "2011", "9999").Returns(true).SetName("Advanced IsMovieAvailable True");
yield return new TestCaseData("title2", "2011", "99929").Returns(false).SetName("Advanced IsMovieAvailable False different title");
yield return new TestCaseData("title", "2001", "99939").Returns(false).SetName("Advanced IsMovieAvailable False different year");
yield return new TestCaseData("title", "2001", "44445").Returns(false).SetName("Advanced IsMovieAvailable False different providerID");
}
}
[TestCaseSource(nameof(IsTvAvailableTestData))]
public bool IsTvAvailableTest(string title, string year)
{
var tv = new List<PlexTvShow>
{
new PlexTvShow {Title = title, ProviderId = null, ReleaseYear = year}
};
var result = Checker.IsTvShowAvailable(tv.ToArray(), "title", "2011");
return result;
}
private static IEnumerable<TestCaseData> IsTvAvailableTestData
{
get
{
yield return new TestCaseData("title", "2011").Returns(true).SetName("IsTvAvailable True");
yield return new TestCaseData("title2", "2011").Returns(false).SetName("IsTvAvailable False different title");
yield return new TestCaseData("title", "2001").Returns(false).SetName("IsTvAvailable False different year");
}
}
[TestCaseSource(nameof(IsTvAvailableAdvancedTestData))]
public bool IsTvAvailableAdvancedTest(string title, string year, string providerId)
{
var movies = new List<PlexTvShow>
{
new PlexTvShow {Title = title, ProviderId = providerId, ReleaseYear = year }
};
var result = Checker.IsTvShowAvailable(movies.ToArray(), "title", "2011", 9999.ToString());
return result;
}
private static IEnumerable<TestCaseData> IsTvAvailableAdvancedTestData
{
get
{
yield return new TestCaseData("title", "2011", "9999").Returns(true).SetName("Advanced IsTvAvailable True");
yield return new TestCaseData("title2", "2011", "99929").Returns(false).SetName("Advanced IsTvAvailable False different title");
yield return new TestCaseData("title", "2001", "99939").Returns(false).SetName("Advanced IsTvAvailable False different year");
yield return new TestCaseData("title", "2001", "44445").Returns(false).SetName("Advanced IsTvAvailable False different providerID");
}
}
[TestCaseSource(nameof(IsTvAvailableAdvancedSeasonsTestData))]
public bool IsTvAvailableAdvancedSeasonsTest(string title, string year, string providerId, int[] seasons)
{
var movies = new List<PlexTvShow>
{
new PlexTvShow {Title = title, ProviderId = providerId, ReleaseYear = year , Seasons = seasons}
};
var result = Checker.IsTvShowAvailable(movies.ToArray(), "title", "2011", 9999.ToString(), new[] { 1, 2, 3 });
return result;
}
private static IEnumerable<TestCaseData> IsTvAvailableAdvancedSeasonsTestData
{
get
{
yield return new TestCaseData("title", "2011", "9999", new[] { 1, 2, 3 }).Returns(true).SetName("Advanced IsTvSeasonsAvailable True");
yield return new TestCaseData("title2", "2011", "99929", new[] { 5, 6 }).Returns(false).SetName("Advanced IsTvSeasonsAvailable False no seasons");
yield return new TestCaseData("title2", "2011", "9999", new[] { 1, 6 }).Returns(true).SetName("Advanced IsTvSeasonsAvailable true one season");
}
}
[TestCaseSource(nameof(IsEpisodeAvailableTestData))]
public bool IsEpisodeAvailableTest(string providerId, int season, int episode)
{
var expected = new List<PlexEpisodes>
{
new PlexEpisodes {EpisodeNumber = 1, ShowTitle = "The Flash",ProviderId = 23.ToString(), SeasonNumber = 1, EpisodeTitle = "Pilot"}
};
PlexEpisodes.Setup(x => x.Custom(It.IsAny<Func<IDbConnection, IEnumerable<PlexEpisodes>>>())).Returns(expected);
//#region Copyright
//// /************************************************************************
//// Copyright (c) 2016 Jamie Rees
//// File: PlexAvailabilityCheckerTests.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.Data;
//using System.Linq;
//using System.Threading.Tasks;
//using Moq;
//using NUnit.Framework;
//using PlexRequests.Api.Interfaces;
//using PlexRequests.Api.Models.Plex;
//using PlexRequests.Core;
//using PlexRequests.Core.SettingModels;
//using PlexRequests.Services.Interfaces;
//using PlexRequests.Helpers;
//using PlexRequests.Services.Jobs;
//using PlexRequests.Services.Models;
//using PlexRequests.Services.Notification;
//using PlexRequests.Store.Models;
//using PlexRequests.Store.Repository;
//using Ploeh.AutoFixture;
//namespace PlexRequests.Services.Tests
//{
// [TestFixture]
// public class PlexAvailabilityCheckerTests
// {
// public IAvailabilityChecker Checker { get; set; }
// private Fixture F { get; set; } = new Fixture();
// private Mock<ISettingsService<PlexSettings>> SettingsMock { get; set; }
// private Mock<ISettingsService<AuthenticationSettings>> AuthMock { get; set; }
// private Mock<IRequestService> RequestMock { get; set; }
// private Mock<IPlexApi> PlexMock { get; set; }
// private Mock<ICacheProvider> CacheMock { get; set; }
// private Mock<INotificationService> NotificationMock { get; set; }
// private Mock<IJobRecord> JobRec { get; set; }
// private Mock<IRepository<UsersToNotify>> NotifyUsers { get; set; }
// private Mock<IRepository<PlexEpisodes>> PlexEpisodes { get; set; }
// private Mock<INotificationEngine> Engine
// {
// get;
// set;
// }
// [SetUp]
// public void Setup()
// {
// SettingsMock = new Mock<ISettingsService<PlexSettings>>();
// AuthMock = new Mock<ISettingsService<AuthenticationSettings>>();
// RequestMock = new Mock<IRequestService>();
// PlexMock = new Mock<IPlexApi>();
// NotificationMock = new Mock<INotificationService>();
// CacheMock = new Mock<ICacheProvider>();
// NotifyUsers = new Mock<IRepository<UsersToNotify>>();
// PlexEpisodes = new Mock<IRepository<PlexEpisodes>>();
// JobRec = new Mock<IJobRecord>();
// Engine = new Mock<INotificationEngine>();
// Checker = new PlexAvailabilityChecker(SettingsMock.Object, RequestMock.Object, PlexMock.Object, CacheMock.Object, NotificationMock.Object, JobRec.Object, NotifyUsers.Object, PlexEpisodes.Object, Engine.Object);
// }
// [Test]
// public void InvalidSettings()
// {
// Checker.CheckAndUpdateAll();
// PlexMock.Verify(x => x.GetLibrary(It.IsAny<string>(), It.IsAny<Uri>(), It.IsAny<string>()), Times.Never);
// PlexMock.Verify(x => x.GetAccount(It.IsAny<string>()), Times.Never);
// PlexMock.Verify(x => x.GetLibrarySections(It.IsAny<string>(), It.IsAny<Uri>()), Times.Never);
// PlexMock.Verify(x => x.GetStatus(It.IsAny<string>(), It.IsAny<Uri>()), Times.Never);
// PlexMock.Verify(x => x.GetUsers(It.IsAny<string>()), Times.Never);
// }
// [TestCaseSource(nameof(IsMovieAvailableTestData))]
// public bool IsMovieAvailableTest(string title, string year)
// {
// var movies = new List<PlexMovie>
// {
// new PlexMovie {Title = title, ProviderId = null, ReleaseYear = year}
// };
// var result = Checker.IsMovieAvailable(movies.ToArray(), "title", "2011");
// return result;
// }
// private static IEnumerable<TestCaseData> IsMovieAvailableTestData
// {
// get
// {
// yield return new TestCaseData("title", "2011").Returns(true).SetName("IsMovieAvailable True");
// yield return new TestCaseData("title2", "2011").Returns(false).SetName("IsMovieAvailable False different title");
// yield return new TestCaseData("title", "2001").Returns(false).SetName("IsMovieAvailable False different year");
// }
// }
// [TestCaseSource(nameof(IsMovieAvailableAdvancedTestData))]
// public bool IsMovieAvailableAdvancedTest(string title, string year, string providerId)
// {
// var movies = new List<PlexMovie>
// {
// new PlexMovie {Title = title, ProviderId = providerId, ReleaseYear = year }
// };
// var result = Checker.IsMovieAvailable(movies.ToArray(), "title", "2011", 9999.ToString());
// return result;
// }
// private static IEnumerable<TestCaseData> IsMovieAvailableAdvancedTestData
// {
// get
// {
// yield return new TestCaseData("title", "2011", "9999").Returns(true).SetName("Advanced IsMovieAvailable True");
// yield return new TestCaseData("title2", "2011", "99929").Returns(false).SetName("Advanced IsMovieAvailable False different title");
// yield return new TestCaseData("title", "2001", "99939").Returns(false).SetName("Advanced IsMovieAvailable False different year");
// yield return new TestCaseData("title", "2001", "44445").Returns(false).SetName("Advanced IsMovieAvailable False different providerID");
// }
// }
// [TestCaseSource(nameof(IsTvAvailableTestData))]
// public bool IsTvAvailableTest(string title, string year)
// {
// var tv = new List<PlexTvShow>
// {
// new PlexTvShow {Title = title, ProviderId = null, ReleaseYear = year}
// };
// var result = Checker.IsTvShowAvailable(tv.ToArray(), "title", "2011");
// return result;
// }
// private static IEnumerable<TestCaseData> IsTvAvailableTestData
// {
// get
// {
// yield return new TestCaseData("title", "2011").Returns(true).SetName("IsTvAvailable True");
// yield return new TestCaseData("title2", "2011").Returns(false).SetName("IsTvAvailable False different title");
// yield return new TestCaseData("title", "2001").Returns(false).SetName("IsTvAvailable False different year");
// }
// }
// [TestCaseSource(nameof(IsTvAvailableAdvancedTestData))]
// public bool IsTvAvailableAdvancedTest(string title, string year, string providerId)
// {
// var movies = new List<PlexTvShow>
// {
// new PlexTvShow {Title = title, ProviderId = providerId, ReleaseYear = year }
// };
// var result = Checker.IsTvShowAvailable(movies.ToArray(), "title", "2011", 9999.ToString());
// return result;
// }
// private static IEnumerable<TestCaseData> IsTvAvailableAdvancedTestData
// {
// get
// {
// yield return new TestCaseData("title", "2011", "9999").Returns(true).SetName("Advanced IsTvAvailable True");
// yield return new TestCaseData("title2", "2011", "99929").Returns(false).SetName("Advanced IsTvAvailable False different title");
// yield return new TestCaseData("title", "2001", "99939").Returns(false).SetName("Advanced IsTvAvailable False different year");
// yield return new TestCaseData("title", "2001", "44445").Returns(false).SetName("Advanced IsTvAvailable False different providerID");
// }
// }
// [TestCaseSource(nameof(IsTvAvailableAdvancedSeasonsTestData))]
// public bool IsTvAvailableAdvancedSeasonsTest(string title, string year, string providerId, int[] seasons)
// {
// var movies = new List<PlexTvShow>
// {
// new PlexTvShow {Title = title, ProviderId = providerId, ReleaseYear = year , Seasons = seasons}
// };
// var result = Checker.IsTvShowAvailable(movies.ToArray(), "title", "2011", 9999.ToString(), new[] { 1, 2, 3 });
// return result;
// }
// private static IEnumerable<TestCaseData> IsTvAvailableAdvancedSeasonsTestData
// {
// get
// {
// yield return new TestCaseData("title", "2011", "9999", new[] { 1, 2, 3 }).Returns(true).SetName("Advanced IsTvSeasonsAvailable True");
// yield return new TestCaseData("title2", "2011", "99929", new[] { 5, 6 }).Returns(false).SetName("Advanced IsTvSeasonsAvailable False no seasons");
// yield return new TestCaseData("title2", "2011", "9999", new[] { 1, 6 }).Returns(true).SetName("Advanced IsTvSeasonsAvailable true one season");
// }
// }
// [TestCaseSource(nameof(IsEpisodeAvailableTestData))]
// public bool IsEpisodeAvailableTest(string providerId, int season, int episode)
// {
// var expected = new List<PlexEpisodes>
// {
// new PlexEpisodes {EpisodeNumber = 1, ShowTitle = "The Flash",ProviderId = 23.ToString(), SeasonNumber = 1, EpisodeTitle = "Pilot"}
// };
// PlexEpisodes.Setup(x => x.Custom(It.IsAny<Func<IDbConnection, IEnumerable<PlexEpisodes>>>())).Returns(expected);
var result = Checker.IsEpisodeAvailable(providerId, season, episode);
return result;
}
private static IEnumerable<TestCaseData> IsEpisodeAvailableTestData
{
get
{
yield return new TestCaseData("23", 1, 1).Returns(true).SetName("IsEpisodeAvailable True S01E01");
yield return new TestCaseData("23", 1, 2).Returns(false).SetName("IsEpisodeAvailable False S01E02");
yield return new TestCaseData("23", 99, 99).Returns(false).SetName("IsEpisodeAvailable False S99E99");
yield return new TestCaseData("230", 99, 99).Returns(false).SetName("IsEpisodeAvailable False Incorrect ProviderId");
}
}
[Test]
public void GetPlexMoviesTests()
{
var cachedMovies = F.Build<PlexSearch>().Without(x => x.Directory).CreateMany().ToList();
cachedMovies.Add(new PlexSearch
{
Video = new List<Video>
{
new Video {Type = "movie", Title = "title1", Year = "2016", ProviderId = "1212"}
}
});
CacheMock.Setup(x => x.Get<List<PlexSearch>>(CacheKeys.PlexLibaries)).Returns(cachedMovies);
SettingsMock.Setup(x => x.GetSettings()).Returns(F.Create<PlexSettings>());
var movies = Checker.GetPlexMovies();
Assert.That(movies.Any(x => x.ProviderId == "1212"));
}
[Test]
public void GetPlexTvShowsTests()
{
var cachedTv = F.Build<PlexSearch>().Without(x => x.Directory).CreateMany().ToList();
cachedTv.Add(new PlexSearch
{
Directory = new List<Directory1>
{
new Directory1 {Type = "show", Title = "title1", Year = "2016", ProviderId = "1212", Seasons = new List<Directory1>()}
}
});
SettingsMock.Setup(x => x.GetSettings()).Returns(F.Create<PlexSettings>());
CacheMock.Setup(x => x.Get<List<PlexSearch>>(CacheKeys.PlexLibaries)).Returns(cachedTv);
var movies = Checker.GetPlexTvShows();
Assert.That(movies.Any(x => x.ProviderId == "1212"));
}
[Test]
public async Task GetAllPlexEpisodes()
{
PlexEpisodes.Setup(x => x.GetAllAsync()).ReturnsAsync(F.CreateMany<PlexEpisodes>().ToList());
var episodes = await Checker.GetEpisodes();
Assert.That(episodes.Count(), Is.GreaterThan(0));
}
}
}
// var result = Checker.IsEpisodeAvailable(providerId, season, episode);
// return result;
// }
// private static IEnumerable<TestCaseData> IsEpisodeAvailableTestData
// {
// get
// {
// yield return new TestCaseData("23", 1, 1).Returns(true).SetName("IsEpisodeAvailable True S01E01");
// yield return new TestCaseData("23", 1, 2).Returns(false).SetName("IsEpisodeAvailable False S01E02");
// yield return new TestCaseData("23", 99, 99).Returns(false).SetName("IsEpisodeAvailable False S99E99");
// yield return new TestCaseData("230", 99, 99).Returns(false).SetName("IsEpisodeAvailable False Incorrect ProviderId");
// }
// }
// [Test]
// public void GetPlexMoviesTests()
// {
// var cachedMovies = F.Build<PlexSearch>().Without(x => x.Directory).CreateMany().ToList();
// cachedMovies.Add(new PlexSearch
// {
// Video = new List<Video>
// {
// new Video {Type = "movie", Title = "title1", Year = "2016", ProviderId = "1212"}
// }
// });
// CacheMock.Setup(x => x.Get<List<PlexSearch>>(CacheKeys.PlexLibaries)).Returns(cachedMovies);
// SettingsMock.Setup(x => x.GetSettings()).Returns(F.Create<PlexSettings>());
// var movies = Checker.GetPlexMovies();
// Assert.That(movies.Any(x => x.ProviderId == "1212"));
// }
// [Test]
// public void GetPlexTvShowsTests()
// {
// var cachedTv = F.Build<PlexSearch>().Without(x => x.Directory).CreateMany().ToList();
// cachedTv.Add(new PlexSearch
// {
// Directory = new List<Directory1>
// {
// new Directory1 {Type = "show", Title = "title1", Year = "2016", ProviderId = "1212", Seasons = new List<Directory1>()}
// }
// });
// SettingsMock.Setup(x => x.GetSettings()).Returns(F.Create<PlexSettings>());
// CacheMock.Setup(x => x.Get<List<PlexSearch>>(CacheKeys.PlexLibaries)).Returns(cachedTv);
// var movies = Checker.GetPlexTvShows();
// Assert.That(movies.Any(x => x.ProviderId == "1212"));
// }
// [Test]
// public async Task GetAllPlexEpisodes()
// {
// PlexEpisodes.Setup(x => x.GetAllAsync()).ReturnsAsync(F.CreateMany<PlexEpisodes>().ToList());
// var episodes = await Checker.GetEpisodes();
// Assert.That(episodes.Count(), Is.GreaterThan(0));
// }
// }
//}

@ -33,6 +33,7 @@ namespace PlexRequests.Services.Jobs
public const string SonarrCacher = "Sonarr Cacher";
public const string SrCacher = "SickRage Cacher";
public const string PlexChecker = "Plex Availability Cacher";
public const string PlexCacher = "Plex Cacher";
public const string StoreCleanup = "Database Cleanup";
public const string RequestLimitReset = "Request Limit Reset";
public const string EpisodeCacher = "Plex Episode Cacher";

@ -44,6 +44,7 @@ using PlexRequests.Services.Models;
using PlexRequests.Services.Notification;
using PlexRequests.Store;
using PlexRequests.Store.Models;
using PlexRequests.Store.Models.Plex;
using PlexRequests.Store.Repository;
using Quartz;
@ -53,7 +54,7 @@ namespace PlexRequests.Services.Jobs
public class PlexAvailabilityChecker : IJob, IAvailabilityChecker
{
public PlexAvailabilityChecker(ISettingsService<PlexSettings> plexSettings, IRequestService request, IPlexApi plex, ICacheProvider cache,
INotificationService notify, IJobRecord rec, IRepository<UsersToNotify> users, IRepository<PlexEpisodes> repo, INotificationEngine e)
INotificationService notify, IJobRecord rec, IRepository<UsersToNotify> users, IRepository<PlexEpisodes> repo, INotificationEngine e, IRepository<PlexContent> content)
{
Plex = plexSettings;
RequestService = request;
@ -64,6 +65,7 @@ namespace PlexRequests.Services.Jobs
UserNotifyRepo = users;
EpisodeRepo = repo;
NotificationEngine = e;
PlexContent = content;
}
private ISettingsService<PlexSettings> Plex { get; }
@ -76,7 +78,7 @@ namespace PlexRequests.Services.Jobs
private IJobRecord Job { get; }
private IRepository<UsersToNotify> UserNotifyRepo { get; }
private INotificationEngine NotificationEngine { get; }
private IRepository<PlexContent> PlexContent { get; }
public void CheckAndUpdateAll()
{

@ -0,0 +1,345 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: PlexAvailabilityChecker.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 System.Threading.Tasks;
using Dapper;
using NLog;
using Org.BouncyCastle.Crypto.Modes.Gcm;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Plex;
using PlexRequests.Core;
using PlexRequests.Core.Models;
using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers;
using PlexRequests.Services.Interfaces;
using PlexRequests.Services.Models;
using PlexRequests.Services.Notification;
using PlexRequests.Store;
using PlexRequests.Store.Models;
using PlexRequests.Store.Models.Plex;
using PlexRequests.Store.Repository;
using Quartz;
namespace PlexRequests.Services.Jobs
{
public class PlexContentCacher : IJob
{
public PlexContentCacher(ISettingsService<PlexSettings> plexSettings, IRequestService request, IPlexApi plex, ICacheProvider cache,
INotificationService notify, IJobRecord rec, IRepository<UsersToNotify> users, IRepository<PlexEpisodes> repo, INotificationEngine e, IRepository<PlexContent> content)
{
Plex = plexSettings;
RequestService = request;
PlexApi = plex;
Cache = cache;
Notification = notify;
Job = rec;
UserNotifyRepo = users;
EpisodeRepo = repo;
NotificationEngine = e;
PlexContent = content;
}
private ISettingsService<PlexSettings> Plex { get; }
private IRepository<PlexEpisodes> EpisodeRepo { get; }
private IRequestService RequestService { get; }
private static Logger Log = LogManager.GetCurrentClassLogger();
private IPlexApi PlexApi { get; }
private ICacheProvider Cache { get; }
private INotificationService Notification { get; }
private IJobRecord Job { get; }
private IRepository<UsersToNotify> UserNotifyRepo { get; }
private INotificationEngine NotificationEngine { get; }
private IRepository<PlexContent> PlexContent { get; }
public void CacheContent()
{
var plexSettings = Plex.GetSettings();
if (!ValidateSettings(plexSettings))
{
Log.Debug("Validation of the plex settings failed.");
return;
}
var libraries = CachedLibraries(plexSettings);
if (libraries == null || !libraries.Any())
{
Log.Debug("Did not find any libraries in Plex.");
return;
}
}
public List<PlexMovie> GetPlexMovies(List<PlexSearch> libs)
{
var settings = Plex.GetSettings();
var movies = new List<PlexMovie>();
if (libs != null)
{
var movieLibs = libs.Where(x =>
x.Video.Any(y =>
y.Type.Equals(PlexMediaType.Movie.ToString(), StringComparison.CurrentCultureIgnoreCase)
)
).ToArray();
foreach (var lib in movieLibs)
{
movies.AddRange(lib.Video.Select(video => new PlexMovie
{
Id = video.Guid,
ReleaseYear = video.Year,
Title = video.Title,
ProviderId = video.ProviderId,
Url = PlexHelper.GetPlexMediaUrl(settings.MachineIdentifier, video.RatingKey)
}));
}
}
return movies;
}
public List<PlexTvShow> GetPlexTvShows(List<PlexSearch> libs)
{
var settings = Plex.GetSettings();
var shows = new List<PlexTvShow>();
if (libs != null)
{
var withDir = libs.Where(x => x.Directory != null);
var tvLibs = withDir.Where(x =>
x.Directory.Any(y =>
y.Type.Equals(PlexMediaType.Show.ToString(), StringComparison.CurrentCultureIgnoreCase)
)
).ToArray();
foreach (var lib in tvLibs)
{
shows.AddRange(lib.Directory.Select(x => new PlexTvShow // shows are in the directory list
{
Title = x.Title,
ReleaseYear = x.Year,
ProviderId = x.ProviderId,
Seasons = x.Seasons?.Select(d => PlexHelper.GetSeasonNumberFromTitle(d.Title)).ToArray(),
Url = PlexHelper.GetPlexMediaUrl(settings.MachineIdentifier, x.RatingKey),
Id = x.Guid
}));
}
}
return shows;
}
public List<PlexAlbum> GetPlexAlbums(List<PlexSearch> libs)
{
var settings = Plex.GetSettings();
var albums = new List<PlexAlbum>();
if (libs != null)
{
var albumLibs = libs.Where(x =>
x.Directory.Any(y =>
y.Type.Equals(PlexMediaType.Artist.ToString(), StringComparison.CurrentCultureIgnoreCase)
)
).ToArray();
foreach (var lib in albumLibs)
{
albums.AddRange(lib.Directory.Select(x => new PlexAlbum()
{
Title = x.Title,
Id = x.Guid,
ProviderId = x.ProviderId,
ReleaseYear = x.Year,
Artist = x.ParentTitle,
Url = PlexHelper.GetPlexMediaUrl(settings.MachineIdentifier, x.RatingKey)
}));
}
}
return albums;
}
private List<PlexSearch> CachedLibraries(PlexSettings plexSettings)
{
var results = new List<PlexSearch>();
if (!ValidateSettings(plexSettings))
{
Log.Warn("The settings are not configured");
return results; // don't error out here, just let it go! let it goo!!!
}
try
{
results = GetLibraries(plexSettings);
if (plexSettings.AdvancedSearch)
{
foreach (PlexSearch t in results)
{
foreach (Directory1 t1 in t.Directory)
{
var currentItem = t1;
var metaData = PlexApi.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri,
currentItem.RatingKey);
// Get the seasons for each show
if (currentItem.Type.Equals(PlexMediaType.Show.ToString(), StringComparison.CurrentCultureIgnoreCase))
{
var seasons = PlexApi.GetSeasons(plexSettings.PlexAuthToken, plexSettings.FullUri,
currentItem.RatingKey);
// We do not want "all episodes" this as a season
var filtered = seasons.Directory.Where(x => !x.Title.Equals("All episodes", StringComparison.CurrentCultureIgnoreCase));
t1.Seasons.AddRange(filtered);
}
var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Directory.Guid);
t1.ProviderId = providerId;
}
foreach (Video t1 in t.Video)
{
var currentItem = t1;
var metaData = PlexApi.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri,
currentItem.RatingKey);
var providerId = PlexHelper.GetProviderIdFromPlexGuid(metaData.Video.Guid);
t1.ProviderId = providerId;
}
}
}
if (results != null)
{
var movies = GetPlexMovies(results);
foreach (var m in movies)
{
PlexContent.Insert(new PlexContent
{
ProviderId = m.ProviderId,
ReleaseYear = m.ReleaseYear,
Title = m.Title,
Type = Store.Models.Plex.PlexMediaType.Movie,
Url = m.Url,
PlexId = m.Id
});
}
var tv = GetPlexTvShows(results);
foreach (var t in tv)
{
PlexContent.Insert(new PlexContent
{
ProviderId = t.ProviderId,
ReleaseYear = t.ReleaseYear,
Title = t.Title,
Type = Store.Models.Plex.PlexMediaType.Show,
Url = t.Url,
Seasons = t.Seasons,
PlexId = t.Id
});
}
var albums = GetPlexAlbums(results);
foreach (var a in albums)
{
PlexContent.Insert(new PlexContent
{
ProviderId = a.ProviderId,
ReleaseYear = a.ReleaseYear,
Title = a.Title,
Type = Store.Models.Plex.PlexMediaType.Artist,
Url = a.Url,
PlexId = a.Id
});
}
}
}
catch (Exception ex)
{
Log.Error(ex, "Failed to obtain Plex libraries");
}
return results;
}
private List<PlexSearch> GetLibraries(PlexSettings plexSettings)
{
var sections = PlexApi.GetLibrarySections(plexSettings.PlexAuthToken, plexSettings.FullUri);
var libs = new List<PlexSearch>();
if (sections != null)
{
foreach (var dir in sections.Directories ?? new List<Directory>())
{
var lib = PlexApi.GetLibrary(plexSettings.PlexAuthToken, plexSettings.FullUri, dir.Key);
if (lib != null)
{
libs.Add(lib);
}
}
}
return libs;
}
private bool ValidateSettings(PlexSettings plex)
{
if (plex?.Ip == null || plex?.PlexAuthToken == null)
{
Log.Warn("A setting is null, Ensure Plex is configured correctly, and we have a Plex Auth token.");
return false;
}
return true;
}
public void Execute(IJobExecutionContext context)
{
Job.SetRunning(true, JobNames.PlexCacher);
try
{
CacheContent();
}
catch (Exception e)
{
Log.Error(e);
}
finally
{
Job.Record(JobNames.PlexCacher);
Job.SetRunning(false, JobNames.PlexCacher);
}
}
}
}

@ -6,5 +6,7 @@
public string Artist { get; set; }
public string ReleaseYear { get; set; }
public string Url { get; set; }
public string ProviderId { get; set; }
public string Id { get; set; }
}
}

@ -2,6 +2,7 @@
{
public class PlexMovie
{
public string Id { get; set; }
public string Title { get; set; }
public string ReleaseYear { get; set; }
public string ProviderId { get; set; }

@ -2,6 +2,7 @@
{
public class PlexTvShow
{
public string Id { get; set; }
public string Title { get; set; }
public string ReleaseYear { get; set; }
public string ProviderId { get; set; }

@ -84,6 +84,7 @@
<Compile Include="Jobs\IRecentlyAdded.cs" />
<Compile Include="Jobs\JobRecord.cs" />
<Compile Include="Jobs\JobNames.cs" />
<Compile Include="Jobs\PlexContentCacher.cs" />
<Compile Include="Jobs\PlexEpisodeCacher.cs" />
<Compile Include="Jobs\RecentlyAdded.cs" />
<Compile Include="Jobs\StoreBackup.cs" />

@ -0,0 +1,53 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: PlexContent.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.Data.Linq.Mapping;
namespace PlexRequests.Store.Models.Plex
{
[Table(Name = nameof(PlexContent))]
public class PlexContent : Entity
{
public string Title { get; set; }
public string ReleaseYear { get; set; }
public string ProviderId { get; set; }
public PlexMediaType Type { get; set; }
public string Url { get; set; }
public string PlexId { get; set; }
/// <summary>
/// Only used for TV Shows
/// </summary>
public int[] Seasons { get; set; }
/// <summary>
/// Only used for Albums
/// </summary>
public string Artist { get; set; }
}
}

@ -0,0 +1,35 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: PlexMediaType .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
namespace PlexRequests.Store.Models.Plex
{
public enum PlexMediaType
{
Movie,
Show,
Artist
}
}

@ -69,6 +69,8 @@
<Compile Include="Models\PlexEpisodes.cs" />
<Compile Include="Models\PlexUsers.cs" />
<Compile Include="Models\Plex\MetadataItems.cs" />
<Compile Include="Models\Plex\PlexContent.cs" />
<Compile Include="Models\Plex\PlexMediaType .cs" />
<Compile Include="Models\RequestQueue.cs" />
<Compile Include="Models\ScheduledJobs.cs" />
<Compile Include="Models\RequestLimit.cs" />

@ -147,4 +147,18 @@ CREATE TABLE IF NOT EXISTS RequestFaultQueue
);
CREATE UNIQUE INDEX IF NOT EXISTS PlexUsers_Id ON PlexUsers (Id);
CREATE TABLE IF NOT EXISTS PlexContent
(
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Title VARCHAR(100) NOT NULL,
ReleaseYear VARCHAR(100) NOT NULL,
ProviderId VARCHAR(100) NOT NULL,
Url VARCHAR(100) NOT NULL,
PlexId VARCHAR(100) NOT NULL,
Artist VARCHAR(100),
Seasons BLOB,
Type INTEGER NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS PlexContent_Id ON PlexContent (Id);
COMMIT;

@ -192,12 +192,17 @@ namespace PlexRequests.UI.Helpers
{
return ctx =>
{
Response response = null;
Response response = new Response
{
StatusCode = HttpStatusCode.OK
};
if (!test(ctx))
{
response = new Response
{
StatusCode = statusCode
};
}
return response;
};
}

@ -40,6 +40,7 @@ using Nancy.Security;
using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers;
using PlexRequests.Helpers.Permissions;
using PlexRequests.Store;
using PlexRequests.Store.Repository;
using PlexRequests.UI.Models;
@ -135,7 +136,7 @@ namespace PlexRequests.UI.Modules
? $"~/{BaseUrl}/register?error=true"
: "~/register?error=true");
}
var userId = UserMapper.CreateAdmin(username, Request.Form.Password);
var userId = UserMapper.CreateUser(username, Request.Form.Password, EnumHelper<Permissions>.All(), 0);
Session[SessionKeys.UsernameKey] = username;
return this.LoginAndRedirect((Guid)userId);
};

@ -40,6 +40,7 @@ using PlexRequests.Core;
using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers;
using PlexRequests.Helpers.Analytics;
using PlexRequests.Helpers.Permissions;
using PlexRequests.UI.Helpers;
using PlexRequests.UI.Models;
@ -185,7 +186,7 @@ namespace PlexRequests.UI.Modules
private async Task<Response> CreateUser()
{
var username = (string)Request.Form.Username;
var userId = Mapper.CreateAdmin(username, Request.Form.Password);
var userId = Mapper.CreateUser(username, Request.Form.Password, EnumHelper<Permissions>.All(), 0);
Analytics.TrackEventAsync(Category.Wizard, Action.Finish, "Finished the wizard", username, CookieHelper.GetAnalyticClientId(Cookies));
Session[SessionKeys.UsernameKey] = username;

Loading…
Cancel
Save