Fixed the plex friends. Added some unit tests, moved the plex auth into it's own page

pull/13/head
tidusjar 9 years ago
parent d6f3f7b750
commit 07beddc26a

@ -33,5 +33,6 @@ namespace PlexRequests.Api.Interfaces
public interface IApiRequest
{
T Execute<T>(IRestRequest request, Uri baseUri) where T : new();
T ExecuteXml<T>(IRestRequest request, Uri baseUri) where T : class;
}
}

@ -25,8 +25,13 @@
// ************************************************************************/
#endregion
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models;
using RestSharp;
@ -57,5 +62,29 @@ namespace PlexRequests.Api
return response.Data;
}
public T ExecuteXml<T>(IRestRequest request, Uri baseUri) where T : class
{
var client = new RestClient { BaseUrl = baseUri };
var response = client.Execute(request);
if (response.ErrorException != null)
{
var message = "Error retrieving response. Check inner details for more info.";
throw new ApplicationException(message, response.ErrorException);
}
return Deserialize<T>(response.Content);
}
public T Deserialize<T>(string input)
where T : class
{
var ser = new XmlSerializer(typeof(T));
using (var sr = new StringReader(input))
return (T)ser.Deserialize(sr);
}
}
}

@ -71,7 +71,7 @@ namespace PlexRequests.Api.Models
public class PlexFriends
{
[XmlElement(ElementName = "User")]
public List<UserFriends> User { get; set; }
public UserFriends[] User { get; set; }
[XmlAttribute(AttributeName = "friendlyName")]
public string FriendlyName { get; set; }
[XmlAttribute(AttributeName = "identifier")]

@ -27,6 +27,7 @@
using System;
using PlexRequests.Api.Models;
using PlexRequests.Helpers;
using RestSharp;
@ -34,6 +35,12 @@ namespace PlexRequests.Api
{
public class PlexApi
{
static PlexApi()
{
Version = AssemblyHelper.GetAssemblyVersion();
}
private static string Version { get; set; }
public PlexAuthentication GetToken(string username, string password)
{
var userModel = new PlexUserRequest
@ -51,7 +58,7 @@ namespace PlexRequests.Api
request.AddHeader("X-Plex-Client-Identifier", "Test213"); // TODO need something unique to the users version/installation
request.AddHeader("X-Plex-Product", "Request Plex");
request.AddHeader("X-Plex-Version", "0.0.1");
request.AddHeader("X-Plex-Version", Version);
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(userModel);
@ -69,12 +76,12 @@ namespace PlexRequests.Api
request.AddHeader("X-Plex-Client-Identifier", "Test213");
request.AddHeader("X-Plex-Product", "Request Plex");
request.AddHeader("X-Plex-Version", "0.0.1");
request.AddHeader("X-Plex-Version", Version);
request.AddHeader("X-Plex-Token", authToken);
request.AddHeader("Content-Type", "application/xml");
var api = new ApiRequest();
var users = api.Execute<PlexFriends>(request, new Uri("https://plex.tv/pms/friends/all"));
var users = api.ExecuteXml<PlexFriends>(request, new Uri("https://plex.tv/pms/friends/all"));
return users;
}

@ -0,0 +1,59 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: AuthenticationSettingsTests.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 NUnit.Framework;
using PlexRequests.Core.SettingModels;
namespace PlexRequests.Core.Tests
{
[TestFixture]
public class AuthenticationSettingsTests
{
[Test, TestCaseSource(nameof(UserData))]
public void DeniedUserListTest(string users, string[] expected)
{
var model = new AuthenticationSettings { DeniedUsers = users };
var result = model.DeniedUserList;
Assert.That(result.Count, Is.EqualTo(expected.Length));
for (var i = 0; i < expected.Length; i++)
{
Assert.That(result[i], Is.EqualTo(expected[i]));
}
}
static readonly object[] UserData =
{
new object[] { "john", new [] {"john"} },
new object[] { "john , abc ,", new [] {"john", "abc"} },
new object[] { "john,, cde", new [] {"john", "cde"} },
new object[] { "john,,, aaa , baaa , ", new [] {"john","aaa","baaa"} },
new object[] { "john, aaa , baaa , maaa, caaa", new [] {"john","aaa","baaa", "maaa", "caaa"} },
};
}
}

@ -0,0 +1,100 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FCFECD5D-47F6-454D-8692-E27A921BE655}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>PlexRequests.Core.Tests</RootNamespace>
<AssemblyName>PlexRequests.Core.Tests</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Moq, Version=4.2.1510.2205, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\packages\Moq.4.2.1510.2205\lib\net40\Moq.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="nunit.framework, Version=3.0.5813.39031, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.0.1\lib\net45\nunit.framework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Ploeh.AutoFixture, Version=3.40.0.0, Culture=neutral, PublicKeyToken=b24654c590009d4f, processorArchitecture=MSIL">
<HintPath>..\packages\AutoFixture.3.40.0\lib\net40\Ploeh.AutoFixture.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
</ItemGroup>
<Choose>
<When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
</ItemGroup>
</When>
<Otherwise />
</Choose>
<ItemGroup>
<Compile Include="AuthenticationSettingsTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PlexRequests.Core\PlexRequests.Core.csproj">
<Project>{DD7DC444-D3BF-4027-8AB9-EFC71F5EC581}</Project>
<Name>PlexRequests.Core</Name>
</ProjectReference>
</ItemGroup>
<Choose>
<When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
</ItemGroup>
</When>
</Choose>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PlexRequests.Core.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PlexRequests.Core.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fcfecd5d-47f6-454d-8692-e27a921be655")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="AutoFixture" version="3.40.0" targetFramework="net452" />
<package id="Moq" version="4.2.1510.2205" targetFramework="net452" />
<package id="NUnit" version="3.0.1" targetFramework="net452" />
</packages>

@ -65,10 +65,11 @@
<Compile Include="CacheKeys.cs" />
<Compile Include="ISettingsService.cs" />
<Compile Include="RequestService.cs" />
<Compile Include="SettingModels\AuthenticationSettings.cs" />
<Compile Include="SettingModels\SonarrSettings.cs" />
<Compile Include="SettingModels\SickRageSettings.cs" />
<Compile Include="SettingModels\CouchPotatoSettings.cs" />
<Compile Include="SettingModels\RequestPlexSettings.cs" />
<Compile Include="SettingModels\PlexRequestSettings.cs" />
<Compile Include="SettingModels\Settings.cs" />
<Compile Include="SettingsService.cs" />
<Compile Include="SettingsServiceV2.cs" />

@ -1,7 +1,7 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: RequestPlexSettings.cs
// File: PlexRequestSettings.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
@ -26,11 +26,10 @@
#endregion
namespace PlexRequests.Core.SettingModels
{
public class RequestPlexSettings : Settings
public class PlexRequestSettings : Settings
{
public int Port { get; set; }
public bool UserAuthentication { get; set; }
public string PlexAuthToken { get; set; }
public bool SearchForMovies { get; set; }
public bool SearchForTvShows { get; set; }
public bool RequireApprovial { get; set; }

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A930E2CF-79E2-45F9-B06A-9A719A254CE4}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>PlexRequests.UI.Tests</RootNamespace>
<AssemblyName>PlexRequests.UI.Tests</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Moq, Version=4.2.1510.2205, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\packages\Moq.4.2.1510.2205\lib\net40\Moq.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="nunit.framework, Version=3.0.5813.39031, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.0.1\lib\net45\nunit.framework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Ploeh.AutoFixture, Version=3.40.0.0, Culture=neutral, PublicKeyToken=b24654c590009d4f, processorArchitecture=MSIL">
<HintPath>..\packages\AutoFixture.3.40.0\lib\net40\Ploeh.AutoFixture.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
</ItemGroup>
<Choose>
<When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
</ItemGroup>
</When>
<Otherwise />
</Choose>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Choose>
<When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
</ItemGroup>
</When>
</Choose>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PlexRequests.UI.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PlexRequests.UI.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a930e2cf-79e2-45f9-b06a-9a719a254ce4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="AutoFixture" version="3.40.0" targetFramework="net452" />
<package id="Moq" version="4.2.1510.2205" targetFramework="net452" />
<package id="NUnit" version="3.0.1" targetFramework="net452" />
</packages>

@ -56,8 +56,9 @@ namespace PlexRequests.UI
container.Register<ISettingsRepository, JsonRepository>();
container.Register<ICacheProvider, MemoryCacheProvider>();
container.Register<ISettingsService<RequestPlexSettings>, SettingsServiceV2<RequestPlexSettings>>();
container.Register<ISettingsService<PlexRequestSettings>, SettingsServiceV2<PlexRequestSettings>>();
container.Register<ISettingsService<CouchPotatoSettings>, SettingsServiceV2<CouchPotatoSettings>>();
container.Register<ISettingsService<AuthenticationSettings>, SettingsServiceV2<AuthenticationSettings>>();
container.Register<IRepository<RequestedModel>, GenericRepository<RequestedModel>>();
base.ConfigureRequestContainer(container, context);

@ -42,17 +42,22 @@ namespace PlexRequests.UI.Modules
{
public class AdminModule : NancyModule
{
private ISettingsService<RequestPlexSettings> RpService { get; set; }
private ISettingsService<PlexRequestSettings> RpService { get; set; }
private ISettingsService<CouchPotatoSettings> CpService { get; set; }
public AdminModule(ISettingsService<RequestPlexSettings> rpService, ISettingsService<CouchPotatoSettings> cpService ) : base("admin")
private ISettingsService<AuthenticationSettings> AuthService { get; set; }
public AdminModule(ISettingsService<PlexRequestSettings> rpService, ISettingsService<CouchPotatoSettings> cpService, ISettingsService<AuthenticationSettings> auth) : base("admin")
{
RpService = rpService;
CpService = cpService;
AuthService = auth;
#if !DEBUG
this.RequiresAuthentication();
#endif
Get["/"] = _ => Admin();
Get["/authentication"] = _ => Authentication();
Post["/authentication"] = _ => SaveAuthentication();
Post["/"] = _ => SaveAdmin();
Post["/requestauth"] = _ => RequestAuthToken();
@ -63,6 +68,24 @@ namespace PlexRequests.UI.Modules
Post["/couchpotato"] = _ => SaveCouchPotato();
}
private Negotiator Authentication()
{
var settings = AuthService.GetSettings();
return View["/Authentication", settings];
}
private Response SaveAuthentication()
{
var model = this.Bind<AuthenticationSettings>();
var result = AuthService.SaveSettings(model);
if (result)
{
return Context.GetRedirect("~/admin/authentication");
}
return Context.GetRedirect("~/error"); //TODO create error page
}
private Negotiator Admin()
{
@ -70,12 +93,12 @@ namespace PlexRequests.UI.Modules
var settings = RpService.GetSettings();
model = settings;
return View["/Admin/Settings", model];
return View["/Settings", model];
}
private Response SaveAdmin()
{
var model = this.Bind<RequestPlexSettings>();
var model = this.Bind<PlexRequestSettings>();
RpService.SaveSettings(model);
@ -89,24 +112,24 @@ namespace PlexRequests.UI.Modules
if (string.IsNullOrEmpty(user.username) || string.IsNullOrEmpty(user.password))
{
return Context.GetRedirect("~/admin?error=true");
return Response.AsJson(new { Result = false, Message = "Please provide a valid username and password" });
}
var plex = new PlexApi();
var model = plex.GetToken(user.username, user.password);
var oldSettings = RpService.GetSettings();
var oldSettings = AuthService.GetSettings();
if (oldSettings != null)
{
oldSettings.PlexAuthToken = model.user.authentication_token;
RpService.SaveSettings(oldSettings);
AuthService.SaveSettings(oldSettings);
}
else
{
var newModel = new RequestPlexSettings
var newModel = new AuthenticationSettings
{
PlexAuthToken = model.user.authentication_token
};
RpService.SaveSettings(newModel);
AuthService.SaveSettings(newModel);
}
return Response.AsJson(new {Result = true, AuthToken = model.user.authentication_token});
@ -115,7 +138,7 @@ namespace PlexRequests.UI.Modules
private Response GetUsers()
{
var token = RpService.GetSettings().PlexAuthToken;
var token = AuthService.GetSettings().PlexAuthToken;
var api = new PlexApi();
var users = api.GetUsers(token);
var usernames = users.User.Select(x => x.Username);
@ -130,6 +153,7 @@ namespace PlexRequests.UI.Modules
return View["/Admin/CouchPotato", model];
}
private Response SaveCouchPotato()
{
var couchPotatoSettings = this.Bind<CouchPotatoSettings>();

@ -78,7 +78,7 @@ namespace PlexRequests.UI.Modules
RequestedBy = tv.RequestedBy,
ReleaseYear = tv.ReleaseDate.Year.ToString()
}).ToList();
//TODO check if Available
//TODO check if Available in CP
return Response.AsJson(viewModel);
}
@ -101,7 +101,7 @@ namespace PlexRequests.UI.Modules
RequestedBy = tv.RequestedBy,
ReleaseYear = tv.ReleaseDate.Year.ToString()
}).ToList();
//TODO check if Available
//TODO check if Available in Sonarr
return Response.AsJson(viewModel);
}

@ -244,6 +244,9 @@
<Content Include="Views\UserLogin\Index.cshtml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Views\Admin\Authentication.cshtml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Include="Web.Debug.config">
<DependentUpon>web.config</DependentUpon>
</None>

@ -25,7 +25,6 @@
// ************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Owin.Hosting;
@ -34,8 +33,6 @@ using Mono.Data.Sqlite;
using NLog;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using PlexRequests.Core;
@ -77,7 +74,7 @@ namespace PlexRequests.UI
private static string GetStartupUri()
{
var uri = "http://localhost:3579/";
var service = new SettingsServiceV2<RequestPlexSettings>(new JsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()));
var service = new SettingsServiceV2<PlexRequestSettings>(new JsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()));
var settings = service.GetSettings();
if (settings.Port != 0)
@ -95,9 +92,13 @@ namespace PlexRequests.UI
var config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
var databaseTarget = new DatabaseTarget { CommandType = CommandType.Text,ConnectionString = connectionString,
var databaseTarget = new DatabaseTarget
{
CommandType = CommandType.Text,
ConnectionString = connectionString,
DBProvider = "Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756",
Name = "database"};
Name = "database"
};
var messageParam = new DatabaseParameterInfo { Name = "@Message", Layout = "${message}" };
@ -131,7 +132,7 @@ namespace PlexRequests.UI
}
catch (Exception e)
{
throw;
}

@ -0,0 +1,157 @@
@Html.Partial("/Admin/_Sidebar")
<div class="col-sm-8">
<form class="form-horizontal" method="POST" action="/admin/SaveAuthentication" id="mainForm">
<fieldset>
<legend>Authentication Settings</legend>
<div class="form-group">
<label for="userAuth" class="col-lg-2 control-label">Enable User Authentication</label>
<div class="col-lg-4 checkbox">
<label>
@if (Model.UserAuthentication)
{
<input type="checkbox" id="userAuth" name="UserAuthentication" checked="checked">
}
else
{
<input type="checkbox" id="userAuth" name="UserAuthentication">
}
</label>
</div>
</div>
<div class="form-group">
<label for="userAuth" class="col-lg-2 control-label">Require users to login with their passwords</label>
<div class="col-lg-4 checkbox">
<label>
@if (Model.UsePassword)
{
<input type="checkbox" id="UsePassword" name="UsePassword" checked="checked">
}
else
{
<input type="checkbox" id="UsePassword" name="UsePassword">
}
</label>
</div>
</div>
<div class="form-group">
<label for="authToken" class="col-lg-2 control-label">Plex Authorization Token</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="authToken" name="PlexAuthToken" placeholder="Plex Auth Token" value="@Model.PlexAuthToken">
</div>
</div>
<div class="form-group">
<label for="username" class="col-lg-2 control-label">Username and Password</label>
<div class="col-lg-4">
<input type="text" class="form-control" id="username" name="Username" placeholder="Username">
</div>
<div class="col-lg-4 col-lg-push-1">
<input type="password" class="form-control" id="password" name="Password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button id="requestToken" class="btn btn-primary">Request Token <i class="fa fa-key"></i></button>
</div>
</div>
<br />
<br />
<small class="col-lg-offset-2">Current users that are allowed to authenticate: </small>
<br />
<br />
<div class="form-group">
<select id="users" multiple="" class="col-lg-10 col-lg-offset-2"></select>
</div>
<div class="form-group">
<br />
<br />
<div class="col-lg-10 col-lg-offset-2">
<button id="refreshUsers" class="btn btn-primary">Refresh Users</button>
</div>
</div>
<br />
<br />
<br />
<br />
<div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
<script>
$(function () {
if ($('#PlexAuthToken')) {
loadUserList();
}
$('#refreshUsers').click(function () {
e.preventDefault();
loadUserList();
});
$('#requestToken').click(function (e) {
e.preventDefault();
var $form = $("#mainForm");
$.ajax({
type: $form.prop("method"),
url: "requestauth",
data: $form.serialize(),
dataType: "json",
success: function (response) {
console.log(response);
if (response.result === true) {
generateNotify("Success!", "success");
$('#authToken').val(response.authToken);
} else {
generateNotify(response.message, "warning");
}
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
}
});
});
function loadUserList() {
$.ajax({
type: "Get",
url: "getusers",
dataType: "json",
success: function (response) {
if (response.length > 1) {
$(response).each(function(user) {
$('#users').append("<option>" + this + "</option>");
});
} else {
$('#users').append("<option>No Users!</option>");
}
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
}
});
}
});
</script>

@ -65,63 +65,6 @@
</div>
</div>
<div class="form-group">
<label for="authToken" class="col-lg-2 control-label">Plex Authorization Token</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="authToken" name="PlexAuthToken" placeholder="Plex Auth Token" value="@Model.PlexAuthToken">
</div>
</div>
<div class="form-group">
<label for="username" class="col-lg-2 control-label">Username and Password</label>
<div class="col-lg-4">
<input type="text" class="form-control" id="username" name="Username" placeholder="Username">
</div>
<div class="col-lg-4 col-lg-push-1">
<input type="password" class="form-control" id="password" name="Password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button id="requestToken" class="btn btn-primary">Request Token</button>
</div>
</div>
<div class="form-group">
<label for="userAuth" class="col-lg-2 control-label">Enable User Authentication</label>
<div class="col-lg-4 checkbox">
<label>
@if (Model.UserAuthentication)
{
<input type="checkbox" id="userAuth" name="UserAuthentication" checked="checked">
}
else
{
<input type="checkbox" id="userAuth" name="UserAuthentication">
}
</label>
</div>
</div>
<br />
<br />
<small class="col-lg-offset-2">Current users that are allowed to authenticate: </small>
<br />
<br />
<div class="form-group">
<select id="users" multiple="" class="col-lg-10 col-lg-offset-2"></select>
</div>
<div class="form-group">
<br />
<br />
<div class="col-lg-10 col-lg-offset-2">
<button id="refreshUsers" class="btn btn-primary">Refresh Users</button>
</div>
</div>
<br />
<br />
<br />
<br />
<div>
</div>
<div class="form-group">
@ -131,68 +74,4 @@
</div>
</fieldset>
</form>
</div>
<script>
$(function () {
if ($('#PlexAuthToken')) {
loadUserList();
}
$('#refreshUsers').click(function () {
loadUserList();
});
$('#requestToken').click(function (e) {
e.preventDefault();
var $form = $("#mainForm");
$.ajax({
type: $form.prop("method"),
url: "admin/requestauth",
data: $form.serialize(),
dataType: "json",
success: function (response) {
console.log(response);
if (response.result === true) {
generateNotify("Success!", "success");
$('#authToken').val(response.authToken);
} else {
generateNotify(response.message, "warning");
}
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
}
});
});
function loadUserList() {
$.ajax({
type: "Get",
url: "admin/getusers",
dataType: "json",
success: function (response) {
if (response.length > 1) {
response.each(function(user) {
$('#users').append("<option>" + user + "</option>");
});
} else {
$('#users').append("<option>No Users!</option>");
}
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
}
});
}
});
</script>
</div>

@ -1,6 +1,7 @@
<div class="col-lg-3 col-md-3 col-sm-4">
<div class="list-group table-of-contents">
<a class="list-group-item" href="/admin">Request Plex Settings</a>
<a class="list-group-item" href="/admin/authentication">Authentication</a>
<a class="list-group-item" href="/admin/couchpotato">CouchPotato Settings</a>
<a class="list-group-item" href="/admin/sonarr">Sonarr Settings</a>
<a class="list-group-item" href="/admin/sickbeard">Sickbeard Settings</a>

@ -21,6 +21,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlexRequests.Helpers", "PlexRequests.Helpers\PlexRequests.Helpers.csproj", "{1252336D-42A3-482A-804C-836E60173DFA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlexRequests.UI.Tests", "PlexRequests.UI.Tests\PlexRequests.UI.Tests.csproj", "{A930E2CF-79E2-45F9-B06A-9A719A254CE4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlexRequests.Core.Tests", "PlexRequests.Core.Tests\PlexRequests.Core.Tests.csproj", "{FCFECD5D-47F6-454D-8692-E27A921BE655}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -51,6 +55,14 @@ Global
{1252336D-42A3-482A-804C-836E60173DFA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1252336D-42A3-482A-804C-836E60173DFA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1252336D-42A3-482A-804C-836E60173DFA}.Release|Any CPU.Build.0 = Release|Any CPU
{A930E2CF-79E2-45F9-B06A-9A719A254CE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A930E2CF-79E2-45F9-B06A-9A719A254CE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A930E2CF-79E2-45F9-B06A-9A719A254CE4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A930E2CF-79E2-45F9-B06A-9A719A254CE4}.Release|Any CPU.Build.0 = Release|Any CPU
{FCFECD5D-47F6-454D-8692-E27A921BE655}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FCFECD5D-47F6-454D-8692-E27A921BE655}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FCFECD5D-47F6-454D-8692-E27A921BE655}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FCFECD5D-47F6-454D-8692-E27A921BE655}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

Loading…
Cancel
Save