Done most on #59

This commit is contained in:
tidusjar 2016-03-23 13:43:27 +00:00
parent 0585ff73ec
commit c7ac8a7d99
32 changed files with 345 additions and 2283 deletions

View file

@ -32,6 +32,7 @@ using Newtonsoft.Json;
using PlexRequests.Store; using PlexRequests.Store;
using PlexRequests.Store.Models; using PlexRequests.Store.Models;
using PlexRequests.Store.Repository;
namespace PlexRequests.Core namespace PlexRequests.Core
{ {

View file

@ -81,7 +81,6 @@
<Compile Include="SettingModels\CouchPotatoSettings.cs" /> <Compile Include="SettingModels\CouchPotatoSettings.cs" />
<Compile Include="SettingModels\PlexRequestSettings.cs" /> <Compile Include="SettingModels\PlexRequestSettings.cs" />
<Compile Include="SettingModels\Settings.cs" /> <Compile Include="SettingModels\Settings.cs" />
<Compile Include="RequestService.cs" />
<Compile Include="SettingsServiceV2.cs" /> <Compile Include="SettingsServiceV2.cs" />
<Compile Include="Setup.cs" /> <Compile Include="Setup.cs" />
<Compile Include="StatusChecker.cs" /> <Compile Include="StatusChecker.cs" />

View file

@ -1,84 +0,0 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: RequestService.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.Collections.Generic;
using System.Linq;
using PlexRequests.Store;
namespace PlexRequests.Core
{
public class RequestService : IRequestService
{
public RequestService(IRepository<RequestedModel> db)
{
Repo = db;
}
private IRepository<RequestedModel> Repo { get; set; }
public long AddRequest(RequestedModel model)
{
return Repo.Insert(model);
}
public bool CheckRequest(int providerId)
{
return Repo.GetAll().Any(x => x.ProviderId == providerId);
}
public void DeleteRequest(RequestedModel model)
{
var entity = Repo.Get(model.Id);
Repo.Delete(entity);
}
public bool UpdateRequest(RequestedModel model)
{
return Repo.Update(model);
}
/// <summary>
/// Updates all the entities. NOTE: we need to Id to be the original entity
/// </summary>
/// <param name="model">The model.</param>
/// <returns></returns>
public bool BatchUpdate(List<RequestedModel> model)
{
return Repo.UpdateAll(model);
}
public RequestedModel Get(int id)
{
return Repo.Get(id);
}
public IEnumerable<RequestedModel> GetAll()
{
return Repo.GetAll();
}
}
}

View file

@ -30,6 +30,7 @@ using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers; using PlexRequests.Helpers;
using PlexRequests.Store; using PlexRequests.Store;
using PlexRequests.Store.Models; using PlexRequests.Store.Models;
using PlexRequests.Store.Repository;
namespace PlexRequests.Core namespace PlexRequests.Core
{ {

View file

@ -75,7 +75,7 @@ namespace PlexRequests.Core
{ {
var result = new List<long>(); var result = new List<long>();
RequestedModel[] requestedModels; RequestedModel[] requestedModels;
var repo = new GenericRepository<RequestedModel>(Db); var repo = new GenericRepository<RequestedModel>(Db, new MemoryCacheProvider());
try try
{ {
var records = repo.GetAll(); var records = repo.GetAll();

View file

@ -88,12 +88,12 @@ namespace PlexRequests.Core
return users.Any(); return users.Any();
} }
public static Guid? CreateUser(string username, string password) public static Guid? CreateUser(string username, string password, string[] claims = default(string[]))
{ {
var repo = new UserRepository<UsersModel>(Db); var repo = new UserRepository<UsersModel>(Db);
var salt = PasswordHasher.GenerateSalt(); var salt = PasswordHasher.GenerateSalt();
var userModel = new UsersModel { UserName = username, UserGuid = Guid.NewGuid().ToString(), Salt = salt, Hash = PasswordHasher.ComputeHash(password, salt)}; var userModel = new UsersModel { UserName = username, UserGuid = Guid.NewGuid().ToString(), Salt = salt, Hash = PasswordHasher.ComputeHash(password, salt), Claims = claims};
repo.Insert(userModel); repo.Insert(userModel);
var userRecord = repo.Get(userModel.UserGuid); var userRecord = repo.Get(userModel.UserGuid);

View file

@ -25,9 +25,14 @@
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System; using System;
using System.Data;
using Newtonsoft.Json; using Newtonsoft.Json;
using NLog;
using NLog.Config;
using NLog.Targets;
namespace PlexRequests.Helpers namespace PlexRequests.Helpers
{ {
public static class LoggingHelper public static class LoggingHelper
@ -55,5 +60,57 @@ namespace PlexRequests.Helpers
} }
return dumpTarget.ToString(); return dumpTarget.ToString();
} }
public static void ConfigureLogging(string connectionString)
{
LogManager.ThrowExceptions = true;
// Step 1. Create configuration object
var config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
var databaseTarget = new DatabaseTarget
{
CommandType = CommandType.Text,
ConnectionString = connectionString,
DBProvider = "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756",
Name = "database"
};
var messageParam = new DatabaseParameterInfo { Name = "@Message", Layout = "${message}" };
var callsiteParam = new DatabaseParameterInfo { Name = "@Callsite", Layout = "${callsite}" };
var levelParam = new DatabaseParameterInfo { Name = "@Level", Layout = "${level}" };
var dateParam = new DatabaseParameterInfo { Name = "@Date", Layout = "${date}" };
var loggerParam = new DatabaseParameterInfo { Name = "@Logger", Layout = "${logger}" };
var exceptionParam = new DatabaseParameterInfo { Name = "@Exception", Layout = "${exception:tostring}" };
databaseTarget.Parameters.Add(messageParam);
databaseTarget.Parameters.Add(callsiteParam);
databaseTarget.Parameters.Add(levelParam);
databaseTarget.Parameters.Add(dateParam);
databaseTarget.Parameters.Add(loggerParam);
databaseTarget.Parameters.Add(exceptionParam);
databaseTarget.CommandText = "INSERT INTO Logs (Date,Level,Logger, Message, Callsite, Exception) VALUES(@Date,@Level,@Logger, @Message, @Callsite, @Exception);";
config.AddTarget("database", databaseTarget);
// Step 4. Define rules
var rule1 = new LoggingRule("*", LogLevel.Info, databaseTarget);
config.LoggingRules.Add(rule1);
// Step 5. Activate the configuration
LogManager.Configuration = config;
}
public static void ReconfigureLogLevel(LogLevel level)
{
foreach (var rule in LogManager.Configuration.LoggingRules)
{
rule.EnableLoggingForLevel(level);
}
//Call to update existing Loggers created with GetLogger() or
//GetCurrentClassLogger()
LogManager.ReconfigExistingLoggers();
}
} }
} }

View file

@ -35,6 +35,10 @@
<HintPath>..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath> <HintPath>..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private> <Private>True</Private>
</Reference> </Reference>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.2.3\lib\net45\NLog.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Runtime.Caching" /> <Reference Include="System.Runtime.Caching" />

View file

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="Newtonsoft.Json" version="8.0.2" targetFramework="net452" /> <package id="Newtonsoft.Json" version="8.0.2" targetFramework="net452" />
<package id="NLog" version="4.2.3" targetFramework="net46" />
</packages> </packages>

View file

@ -26,11 +26,13 @@
#endregion #endregion
using System; using System;
using Dapper.Contrib.Extensions;
namespace PlexRequests.Store.Models namespace PlexRequests.Store.Models
{ {
[Table("Logs")]
public class LogEntity : Entity public class LogEntity : Entity
{ {
public string Username { get; set; }
public DateTime Date { get; set; } public DateTime Date { get; set; }
public string Level { get; set; } public string Level { get; set; }
public string Logger { get; set; } public string Logger { get; set; }

View file

@ -58,17 +58,17 @@
<ItemGroup> <ItemGroup>
<Compile Include="DbConfiguration.cs" /> <Compile Include="DbConfiguration.cs" />
<Compile Include="Entity.cs" /> <Compile Include="Entity.cs" />
<Compile Include="IRequestRepository.cs" /> <Compile Include="Repository\IRequestRepository.cs" />
<Compile Include="ISettingsRepository.cs" /> <Compile Include="Repository\ISettingsRepository.cs" />
<Compile Include="ISqliteConfiguration.cs" /> <Compile Include="ISqliteConfiguration.cs" />
<Compile Include="IRepository.cs" /> <Compile Include="Repository\IRepository.cs" />
<Compile Include="Models\GlobalSettings.cs" /> <Compile Include="Models\GlobalSettings.cs" />
<Compile Include="Models\LogEntity.cs" /> <Compile Include="Models\LogEntity.cs" />
<Compile Include="Models\RequestBlobs.cs" /> <Compile Include="Models\RequestBlobs.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Repository\SettingsJsonRepository.cs" /> <Compile Include="Repository\SettingsJsonRepository.cs" />
<Compile Include="Repository\RequestJsonRepository.cs" /> <Compile Include="Repository\RequestJsonRepository.cs" />
<Compile Include="GenericRepository.cs" /> <Compile Include="Repository\GenericRepository.cs" />
<Compile Include="RequestedModel.cs" /> <Compile Include="RequestedModel.cs" />
<Compile Include="UserEntity.cs" /> <Compile Include="UserEntity.cs" />
<Compile Include="UsersModel.cs" /> <Compile Include="UsersModel.cs" />

View file

@ -34,20 +34,23 @@ using NLog;
using PlexRequests.Helpers; using PlexRequests.Helpers;
namespace PlexRequests.Store namespace PlexRequests.Store.Repository
{ {
public class GenericRepository<T> : IRepository<T> where T : Entity public class GenericRepository<T> : IRepository<T> where T : Entity
{ {
public GenericRepository(ISqliteConfiguration config) private ICacheProvider Cache { get; }
public GenericRepository(ISqliteConfiguration config, ICacheProvider cache)
{ {
Config = config; Config = config;
Cache = cache;
} }
private static Logger Log = LogManager.GetCurrentClassLogger(); private static Logger Log = LogManager.GetCurrentClassLogger();
private ISqliteConfiguration Config { get; set; } private ISqliteConfiguration Config { get; }
public long Insert(T entity) public long Insert(T entity)
{ {
ResetCache();
using (var cnn = Config.DbConnection()) using (var cnn = Config.DbConnection())
{ {
cnn.Open(); cnn.Open();
@ -57,12 +60,14 @@ namespace PlexRequests.Store
public IEnumerable<T> GetAll() public IEnumerable<T> GetAll()
{ {
using (var db = Config.DbConnection()) using (var db = Config.DbConnection())
{ {
db.Open(); db.Open();
var result = db.GetAll<T>(); var result = db.GetAll<T>();
return result; return result;
} }
} }
public T Get(string id) public T Get(string id)
@ -72,15 +77,23 @@ namespace PlexRequests.Store
public T Get(int id) public T Get(int id)
{ {
using (var db = Config.DbConnection()) var key = "Get" + id;
{ var item = Cache.GetOrSet(
db.Open(); key,
return db.Get<T>(id); () =>
} {
using (var db = Config.DbConnection())
{
db.Open();
return db.Get<T>(id);
}
});
return item;
} }
public void Delete(T entity) public void Delete(T entity)
{ {
ResetCache();
using (var db = Config.DbConnection()) using (var db = Config.DbConnection())
{ {
db.Open(); db.Open();
@ -90,6 +103,7 @@ namespace PlexRequests.Store
public bool Update(T entity) public bool Update(T entity)
{ {
ResetCache();
Log.Trace("Updating entity"); Log.Trace("Updating entity");
Log.Trace(entity.DumpJson()); Log.Trace(entity.DumpJson());
using (var db = Config.DbConnection()) using (var db = Config.DbConnection())
@ -101,6 +115,7 @@ namespace PlexRequests.Store
public bool UpdateAll(IEnumerable<T> entity) public bool UpdateAll(IEnumerable<T> entity)
{ {
ResetCache();
Log.Trace("Updating all entities"); Log.Trace("Updating all entities");
var result = new HashSet<bool>(); var result = new HashSet<bool>();
@ -114,5 +129,11 @@ namespace PlexRequests.Store
} }
return result.All(x => true); return result.All(x => true);
} }
private void ResetCache()
{
Cache.Remove("Get");
Cache.Remove("GetAll");
}
} }
} }

View file

@ -26,7 +26,7 @@
#endregion #endregion
using System.Collections.Generic; using System.Collections.Generic;
namespace PlexRequests.Store namespace PlexRequests.Store.Repository
{ {
public interface IRepository<T> public interface IRepository<T>
{ {

View file

@ -28,7 +28,7 @@ using System.Collections.Generic;
using PlexRequests.Store.Models; using PlexRequests.Store.Models;
namespace PlexRequests.Store namespace PlexRequests.Store.Repository
{ {
public interface IRequestRepository public interface IRequestRepository
{ {

View file

@ -28,7 +28,7 @@ using System.Collections.Generic;
using PlexRequests.Store.Models; using PlexRequests.Store.Models;
namespace PlexRequests.Store namespace PlexRequests.Store.Repository
{ {
public interface ISettingsRepository public interface ISettingsRepository
{ {

View file

@ -30,6 +30,8 @@ using System.Linq;
using Dapper.Contrib.Extensions; using Dapper.Contrib.Extensions;
using PlexRequests.Store.Repository;
namespace PlexRequests.Store namespace PlexRequests.Store
{ {
public class UserRepository<T> : IRepository<T> where T : UserEntity public class UserRepository<T> : IRepository<T> where T : UserEntity

View file

@ -33,5 +33,6 @@ namespace PlexRequests.Store
{ {
public byte[] Hash { get; set; } public byte[] Hash { get; set; }
public byte[] Salt { get; set; } public byte[] Salt { get; set; }
public string[] Claims { get; set; }
} }
} }

View file

@ -39,6 +39,8 @@ using PlexRequests.Api.Interfaces;
using PlexRequests.Api.Models.Plex; using PlexRequests.Api.Models.Plex;
using PlexRequests.Core; using PlexRequests.Core;
using PlexRequests.Core.SettingModels; using PlexRequests.Core.SettingModels;
using PlexRequests.Store.Models;
using PlexRequests.Store.Repository;
using PlexRequests.UI.Models; using PlexRequests.UI.Models;
using PlexRequests.UI.Modules; using PlexRequests.UI.Modules;
@ -59,6 +61,7 @@ namespace PlexRequests.UI.Tests
private Mock<ISonarrApi> SonarrApiMock { get; set; } private Mock<ISonarrApi> SonarrApiMock { get; set; }
private Mock<IPushbulletApi> PushbulletApi { get; set; } private Mock<IPushbulletApi> PushbulletApi { get; set; }
private Mock<ICouchPotatoApi> CpApi { get; set; } private Mock<ICouchPotatoApi> CpApi { get; set; }
private Mock<IRepository<LogEntity>> LogRepo { get; set; }
private ConfigurableBootstrapper Bootstrapper { get; set; } private ConfigurableBootstrapper Bootstrapper { get; set; }
@ -83,6 +86,7 @@ namespace PlexRequests.UI.Tests
PushbulletSettings = new Mock<ISettingsService<PushbulletNotificationSettings>>(); PushbulletSettings = new Mock<ISettingsService<PushbulletNotificationSettings>>();
CpApi = new Mock<ICouchPotatoApi>(); CpApi = new Mock<ICouchPotatoApi>();
SickRageSettingsMock = new Mock<ISettingsService<SickRageSettings>>(); SickRageSettingsMock = new Mock<ISettingsService<SickRageSettings>>();
LogRepo = new Mock<IRepository<LogEntity>>();
Bootstrapper = new ConfigurableBootstrapper(with => Bootstrapper = new ConfigurableBootstrapper(with =>
{ {
@ -99,6 +103,7 @@ namespace PlexRequests.UI.Tests
with.Dependency(PushbulletSettings.Object); with.Dependency(PushbulletSettings.Object);
with.Dependency(CpApi.Object); with.Dependency(CpApi.Object);
with.Dependency(SickRageSettingsMock.Object); with.Dependency(SickRageSettingsMock.Object);
with.Dependency(LogRepo.Object);
with.RootPathProvider<TestRootPathProvider>(); with.RootPathProvider<TestRootPathProvider>();
with.RequestStartup((container, pipelines, context) => with.RequestStartup((container, pipelines, context) =>
{ {

View file

@ -117,6 +117,10 @@
<Project>{566EFA49-68F8-4716-9693-A6B3F2624DEA}</Project> <Project>{566EFA49-68F8-4716-9693-A6B3F2624DEA}</Project>
<Name>PlexRequests.Services</Name> <Name>PlexRequests.Services</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="..\PlexRequests.Store\PlexRequests.Store.csproj">
<Project>{92433867-2B7B-477B-A566-96C382427525}</Project>
<Name>PlexRequests.Store</Name>
</ProjectReference>
<ProjectReference Include="..\PlexRequests.UI\PlexRequests.UI.csproj"> <ProjectReference Include="..\PlexRequests.UI\PlexRequests.UI.csproj">
<Project>{68F5F5F3-B8BB-4911-875F-6F00AAE04EA6}</Project> <Project>{68F5F5F3-B8BB-4911-875F-6F00AAE04EA6}</Project>
<Name>PlexRequests.UI</Name> <Name>PlexRequests.UI</Name>

View file

@ -47,6 +47,7 @@ using PlexRequests.Services;
using PlexRequests.Services.Interfaces; using PlexRequests.Services.Interfaces;
using PlexRequests.Services.Notification; using PlexRequests.Services.Notification;
using PlexRequests.Store; using PlexRequests.Store;
using PlexRequests.Store.Models;
using PlexRequests.Store.Repository; using PlexRequests.Store.Repository;
using PlexRequests.UI.Jobs; using PlexRequests.UI.Jobs;
using TaskFactory = FluentScheduler.TaskFactory; using TaskFactory = FluentScheduler.TaskFactory;
@ -77,6 +78,7 @@ namespace PlexRequests.UI
// Repo's // Repo's
container.Register<IRepository<RequestedModel>, GenericRepository<RequestedModel>>(); container.Register<IRepository<RequestedModel>, GenericRepository<RequestedModel>>();
container.Register<IRepository<LogEntity>, GenericRepository<LogEntity>>();
container.Register<IRequestService, JsonRequestService>(); container.Register<IRequestService, JsonRequestService>();
container.Register<ISettingsRepository, SettingsJsonRepository>(); container.Register<ISettingsRepository, SettingsJsonRepository>();

File diff suppressed because one or more lines are too long

View file

@ -26,6 +26,7 @@
#endregion #endregion
using System.Dynamic; using System.Dynamic;
using System.Linq; using System.Linq;
using System.Web.UI.WebControls;
using MarkdownSharp; using MarkdownSharp;
@ -44,6 +45,8 @@ using PlexRequests.Core;
using PlexRequests.Core.SettingModels; using PlexRequests.Core.SettingModels;
using PlexRequests.Helpers; using PlexRequests.Helpers;
using PlexRequests.Services.Notification; using PlexRequests.Services.Notification;
using PlexRequests.Store.Models;
using PlexRequests.Store.Repository;
using PlexRequests.UI.Helpers; using PlexRequests.UI.Helpers;
using PlexRequests.UI.Models; using PlexRequests.UI.Models;
@ -63,6 +66,7 @@ namespace PlexRequests.UI.Modules
private ISonarrApi SonarrApi { get; } private ISonarrApi SonarrApi { get; }
private PushbulletApi PushbulletApi { get; } private PushbulletApi PushbulletApi { get; }
private ICouchPotatoApi CpApi { get; } private ICouchPotatoApi CpApi { get; }
private IRepository<LogEntity> LogsRepo { get; }
private static Logger Log = LogManager.GetCurrentClassLogger(); private static Logger Log = LogManager.GetCurrentClassLogger();
public AdminModule(ISettingsService<PlexRequestSettings> rpService, public AdminModule(ISettingsService<PlexRequestSettings> rpService,
@ -76,7 +80,8 @@ namespace PlexRequests.UI.Modules
IPlexApi plexApi, IPlexApi plexApi,
ISettingsService<PushbulletNotificationSettings> pbSettings, ISettingsService<PushbulletNotificationSettings> pbSettings,
PushbulletApi pbApi, PushbulletApi pbApi,
ICouchPotatoApi cpApi) : base("admin") ICouchPotatoApi cpApi,
IRepository<LogEntity> logsRepo) : base("admin")
{ {
RpService = rpService; RpService = rpService;
CpService = cpService; CpService = cpService;
@ -90,6 +95,7 @@ namespace PlexRequests.UI.Modules
PushbulletApi = pbApi; PushbulletApi = pbApi;
CpApi = cpApi; CpApi = cpApi;
SickRageService = sickrage; SickRageService = sickrage;
LogsRepo = logsRepo;
#if !DEBUG #if !DEBUG
this.RequiresAuthentication(); this.RequiresAuthentication();
@ -126,6 +132,10 @@ namespace PlexRequests.UI.Modules
Get["/pushbulletnotification"] = _ => PushbulletNotifications(); Get["/pushbulletnotification"] = _ => PushbulletNotifications();
Post["/pushbulletnotification"] = _ => SavePushbulletNotifications(); Post["/pushbulletnotification"] = _ => SavePushbulletNotifications();
Get["/logs"] = _ => Logs();
Get["/loglevel"] = _ => GetLogLevels();
Post["/loglevel"] = _ => UpdateLogLevels(Request.Form.level);
} }
private Negotiator Authentication() private Negotiator Authentication()
@ -246,8 +256,8 @@ namespace PlexRequests.UI.Modules
} }
var result = CpService.SaveSettings(couchPotatoSettings); var result = CpService.SaveSettings(couchPotatoSettings);
return Response.AsJson(result return Response.AsJson(result
? new JsonResponseModel { Result = true, Message = "Successfully Updated the Settings for CouchPotato!" } ? new JsonResponseModel { Result = true, Message = "Successfully Updated the Settings for CouchPotato!" }
: new JsonResponseModel { Result = false, Message = "Could not update the settings, take a look at the logs." }); : new JsonResponseModel { Result = false, Message = "Could not update the settings, take a look at the logs." });
} }
@ -422,5 +432,24 @@ namespace PlexRequests.UI.Modules
return Response.AsJson(profiles); return Response.AsJson(profiles);
} }
private Negotiator Logs()
{
var allLogs = LogsRepo.GetAll().OrderByDescending(x => x.Id).Take(20);
return View["Logs", allLogs];
}
private Response GetLogLevels()
{
var levels = LogManager.Configuration.LoggingRules.FirstOrDefault(x => x.NameMatches("database"));
return Response.AsJson(levels.Levels);
}
private Response UpdateLogLevels(int level)
{
var newLevel = LogLevel.FromOrdinal(level);
LoggingHelper.ReconfigureLogLevel(newLevel);
return Response.AsJson(new JsonResponseModel { Result = true, Message = $"The new log level is now {newLevel}"});
}
} }
} }

View file

@ -169,18 +169,14 @@ namespace PlexRequests.UI.Modules
private Response RequestMovieAndUpdateStatus(RequestedModel request) private Response RequestMovieAndUpdateStatus(RequestedModel request)
{ {
if (!Context.CurrentUser.IsAuthenticated())
{
return Response.AsJson(new JsonResponseModel { Result = false, Message = "You are not an Admin, so you cannot approve any requests." });
}
var cpSettings = CpService.GetSettings(); var cpSettings = CpService.GetSettings();
var cp = new CouchPotatoApi(); var cp = new CouchPotatoApi();
Log.Info("Adding movie to CP : {0}", request.Title); Log.Info("Adding movie to CouchPotato : {0}", request.Title);
if (!cpSettings.Enabled) if (!cpSettings.Enabled)
{ {
// Approve it // Approve it
request.Approved = true; request.Approved = true;
Log.Warn("We approved movie: {0} but could not add it to CouchPotato because it has not been setup", request.Title);
// Update the record // Update the record
var inserted = Service.UpdateRequest(request); var inserted = Service.UpdateRequest(request);
@ -226,6 +222,11 @@ namespace PlexRequests.UI.Modules
/// <returns></returns> /// <returns></returns>
private Response ApproveAll() private Response ApproveAll()
{ {
if (!Context.CurrentUser.IsAuthenticated())
{
return Response.AsJson(new JsonResponseModel { Result = false, Message = "You are not an Admin, so you cannot approve any requests." });
}
var requests = Service.GetAll().Where(x => x.Approved == false); var requests = Service.GetAll().Where(x => x.Approved == false);
var requestedModels = requests as RequestedModel[] ?? requests.ToArray(); var requestedModels = requests as RequestedModel[] ?? requests.ToArray();
if (!requestedModels.Any()) if (!requestedModels.Any())

View file

@ -51,7 +51,7 @@ namespace PlexRequests.UI.Modules
model.AdminExists = adminCreated; model.AdminExists = adminCreated;
return View["Login/Index", model]; return View["Login/Index", model];
} }
}; };
Get["/logout"] = x => this.LogoutAndRedirect("~/"); Get["/logout"] = x => this.LogoutAndRedirect("~/");
@ -76,7 +76,8 @@ namespace PlexRequests.UI.Modules
return this.LoginAndRedirect(userId.Value, expiry); return this.LoginAndRedirect(userId.Value, expiry);
}; };
Get["/register"] = x => { Get["/register"] = x =>
{
{ {
dynamic model = new ExpandoObject(); dynamic model = new ExpandoObject();
model.Errored = Request.Query.error.HasValue; model.Errored = Request.Query.error.HasValue;
@ -87,13 +88,13 @@ namespace PlexRequests.UI.Modules
Post["/register"] = x => Post["/register"] = x =>
{ {
var username = (string) Request.Form.Username; var username = (string)Request.Form.Username;
var exists = UserMapper.DoUsersExist(); var exists = UserMapper.DoUsersExist();
if (exists) if (exists)
{ {
return Context.GetRedirect("~/register?error=true&username=" + username); return Context.GetRedirect("~/register?error=true");
} }
var userId = UserMapper.CreateUser(username, Request.Form.Password); var userId = UserMapper.CreateUser(username, Request.Form.Password, new[] { "Admin" });
Session[SessionKeys.UsernameKey] = username; Session[SessionKeys.UsernameKey] = username;
return this.LoginAndRedirect((Guid)userId); return this.LoginAndRedirect((Guid)userId);
}; };
@ -116,7 +117,7 @@ namespace PlexRequests.UI.Modules
var newPasswordAgain = Request.Form.NewPasswordAgain; var newPasswordAgain = Request.Form.NewPasswordAgain;
if (!newPassword.Equals(newPasswordAgain)) if (!newPassword.Equals(newPasswordAgain))
{ {
} }
var result = UserMapper.UpdateUser(username, oldPass, newPassword); var result = UserMapper.UpdateUser(username, oldPass, newPassword);

View file

@ -13,7 +13,7 @@
layout="${date} ${logger} ${level}: ${message}" /> layout="${date} ${logger} ${level}: ${message}" />
<target name="Database" xsi:type="Database" <!--<target name="Database" xsi:type="Database"
dbProvider="Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756" keepConnection="false" dbProvider="Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756" keepConnection="false"
connectionString="Data Source=PlexRequests.sqlite, version=3" connectionString="Data Source=PlexRequests.sqlite, version=3"
commandText="INSERT into Logs(Date, Level, Logger, Callsite, Message, Exception) commandText="INSERT into Logs(Date, Level, Logger, Callsite, Message, Exception)
@ -24,11 +24,11 @@
<parameter name="@Callsite" layout="${callsite:filename=true}"/> <parameter name="@Callsite" layout="${callsite:filename=true}"/>
<parameter name="@Message" layout="${message}"/> <parameter name="@Message" layout="${message}"/>
<parameter name="@Exception" layout="${exception:format=tostring}"/> <parameter name="@Exception" layout="${exception:format=tostring}"/>
</target> </target>-->
</targets> </targets>
<rules> <rules>
<logger name="*" minlevel="Trace" writeTo="filelog" /> <logger name="*" minlevel="Trace" writeTo="filelog" />
<logger name="*" minlevel="Trace" writeTo="Database" /> <!--<logger name="*" minlevel="Trace" writeTo="Database" />-->
</rules> </rules>
</nlog> </nlog>

View file

@ -97,6 +97,10 @@
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\Assemblies\Mono.Data.Sqlite.dll</HintPath> <HintPath>..\Assemblies\Mono.Data.Sqlite.dll</HintPath>
</Reference> </Reference>
<Reference Include="Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756, processorArchitecture=MSIL">
<HintPath>..\packages\Mono.Posix.4.0.0.0\lib\net40\Mono.Posix.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Nancy, Version=1.4.2.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="Nancy, Version=1.4.2.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Nancy.1.4.3\lib\net40\Nancy.dll</HintPath> <HintPath>..\packages\Nancy.1.4.3\lib\net40\Nancy.dll</HintPath>
<Private>True</Private> <Private>True</Private>
@ -335,6 +339,9 @@
<Content Include="Views\Login\ChangePassword.cshtml"> <Content Include="Views\Login\ChangePassword.cshtml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
<Content Include="Views\Admin\Logs.cshtml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Include="Web.Debug.config"> <None Include="Web.Debug.config">
<DependentUpon>web.config</DependentUpon> <DependentUpon>web.config</DependentUpon>
</None> </None>

View file

@ -30,6 +30,8 @@ using System.Data;
using Microsoft.Owin.Hosting; using Microsoft.Owin.Hosting;
using Mono.Data.Sqlite; using Mono.Data.Sqlite;
using Mono.Unix;
using Mono.Unix.Native;
using NLog; using NLog;
using NLog.Config; using NLog.Config;
@ -55,7 +57,7 @@ namespace PlexRequests.UI
int portResult; int portResult;
if (!int.TryParse(args[0], out portResult)) if (!int.TryParse(args[0], out portResult))
{ {
Console.WriteLine("Incorrect Port format. Press Any Key to shut down."); Console.WriteLine("Incorrect Port format. Press any key.");
Console.ReadLine(); Console.ReadLine();
Environment.Exit(1); Environment.Exit(1);
} }
@ -65,7 +67,8 @@ namespace PlexRequests.UI
WriteOutVersion(); WriteOutVersion();
var s = new Setup(); var s = new Setup();
s.SetupDb(); var cn = s.SetupDb();
ConfigureTargets(cn);
if (port == -1) if (port == -1)
port = GetStartupPort(); port = GetStartupPort();
@ -76,18 +79,29 @@ namespace PlexRequests.UI
}; };
try try
{ {
using (WebApp.Start<Startup>(options))
{
Console.WriteLine($"Request Plex is running on the following: http://+:{port}/");
using (WebApp.Start<Startup>(options)) if (Type.GetType("Mono.Runtime") != null)
{ {
Console.WriteLine($"Request Plex is running on the following port: {port}"); Log.Info("We are on Mono!");
Console.WriteLine("Press any key to exit"); // on mono, processes will usually run as daemons - this allows you to listen
Console.ReadLine(); // for termination signals (ctrl+c, shutdown, etc) and finalize correctly
} UnixSignal.WaitAny(
new[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM), new UnixSignal(Signum.SIGQUIT), new UnixSignal(Signum.SIGHUP) });
}
else
{
Log.Info("This is not Mono");
Console.WriteLine("Press any key to exit");
Console.ReadLine();
}
}
} }
catch (Exception e) catch (Exception e)
{ {
var a = e.Message; Log.Fatal(e);
throw; throw;
} }
} }
@ -116,59 +130,7 @@ namespace PlexRequests.UI
private static void ConfigureTargets(string connectionString) private static void ConfigureTargets(string connectionString)
{ {
LogManager.ThrowExceptions = true; LoggingHelper.ConfigureLogging(connectionString);
// Step 1. Create configuration object
var config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
var databaseTarget = new DatabaseTarget
{
CommandType = CommandType.Text,
ConnectionString = connectionString,
DBProvider = "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756",
Name = "database"
};
var messageParam = new DatabaseParameterInfo { Name = "@Message", Layout = "${message}" };
var callsiteParam = new DatabaseParameterInfo { Name = "@Callsite", Layout = "${callsite}" };
var levelParam = new DatabaseParameterInfo { Name = "@Level", Layout = "${level}" };
var usernameParam = new DatabaseParameterInfo { Name = "@Username", Layout = "${identity}" };
var dateParam = new DatabaseParameterInfo { Name = "@Date", Layout = "${date}" };
var loggerParam = new DatabaseParameterInfo { Name = "@Logger", Layout = "${logger}" };
var exceptionParam = new DatabaseParameterInfo { Name = "@Exception", Layout = "${exception:tostring}" };
databaseTarget.Parameters.Add(messageParam);
databaseTarget.Parameters.Add(callsiteParam);
databaseTarget.Parameters.Add(levelParam);
databaseTarget.Parameters.Add(usernameParam);
databaseTarget.Parameters.Add(dateParam);
databaseTarget.Parameters.Add(loggerParam);
databaseTarget.Parameters.Add(exceptionParam);
databaseTarget.CommandText = "INSERT INTO Log (Username,Date,Level,Logger, Message, Callsite, Exception) VALUES(@Username,@Date,@Level,@Logger, @Message, @Callsite, @Exception);";
config.AddTarget("database", databaseTarget);
// Step 4. Define rules
var rule1 = new LoggingRule("*", LogLevel.Error, databaseTarget);
config.LoggingRules.Add(rule1);
try
{
// Step 5. Activate the configuration
LogManager.Configuration = config;
}
catch (Exception)
{
throw;
}
// Example usage
Logger logger = LogManager.GetLogger("Example");
logger.Error("error log message");
} }
} }
} }

View file

@ -0,0 +1,118 @@
@Html.Partial("_Sidebar")
<div class="col-sm-8 col-sm-push-1">
<fieldset>
<legend>Logs</legend>
<form method="post" id="mainForm" action="/admin/loglevel">
<div class="form-group">
<label for="logLevel" class="control-label">Log Level</label>
<div id="logLevel">
<select class="form-control" id="selected">
<option id="Trace" value="0">Trace</option>
<option id="Debug" value="1">Debug</option>
<option id="Info" value="2">Info</option>
<option id="Warn" value="3">Warn</option>
<option id="Error" value="4">Error</option>
<option id="Fatal" value="5">Fatal</option>
</select>
</div>
</div>
<div class="form-group">
<div>
<button id="save" type="submit" class="btn btn-primary-outline ">Submit</button>
</div>
</div>
</form>
<table class="table table-striped table-hover table-responsive">
<tr>
<th>Message</th>
<th>Logger</th>
<th>Exception</th>
<th>Callsite</th>
<th>Log Level</th>
<th>Date</th>
</tr>
@foreach (var m in Model)
{
<tr>
<td>
@m.Message
</td>
<td>
@m.Logger
</td>
<td>
@m.Exception
</td>
<td>
@m.Callsite
</td>
<td>
@m.Level
</td>
<td>
@m.Date
</td>
</tr>
}
</table>
</fieldset>
</div>
<script>
$(function () {
$.ajax({
type: "get",
url: "/admin/loglevel",
dataType: "json",
success: function (response) {
$("#select > option").each(function (level) {
if (response[0] == level.value) {
$('#' + level.target.id).prop("selected", "selected");
}
});
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
}
});
$('#save').click(function (e) {
e.preventDefault();
var logLevel = $("#logLevel option:selected").val();
var $form = $("#mainForm");
var data = "level=" + logLevel;
$.ajax({
type: $form.prop("method"),
data: data,
url: $form.prop("action"),
dataType: "json",
success: function (response) {
if (response.result === true) {
generateNotify(response.message, "success");
} else {
generateNotify(response.message, "warning");
}
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
}
});
});
});
</script>

View file

@ -70,7 +70,14 @@
{ {
<a class="list-group-item" href="/admin/pushbulletnotification">Pushbullet Notifications</a> <a class="list-group-item" href="/admin/pushbulletnotification">Pushbullet Notifications</a>
} }
@if (Context.Request.Path == "/admin/logs")
{
<a class="list-group-item active" href="/admin/logs">Logs</a>
}
else
{
<a class="list-group-item" href="/admin/logs">Logs</a>
}
@if (Context.Request.Path == "/admin/status") @if (Context.Request.Path == "/admin/status")
{ {
<a class="list-group-item active" href="/admin/status">Status</a> <a class="list-group-item active" href="/admin/status">Status</a>

View file

@ -57,26 +57,26 @@
{ {
<li><a href="/requests">Requests</a></li> <li><a href="/requests">Requests</a></li>
} }
@if (Context.CurrentUser.IsAuthenticated())
{
if (Context.Request.Path == "/admin")
{
<li class="active"><a href="/admin">Admin</a></li>
}
else
{
<li><a href="/admin">Admin</a></li>
}
}
</ul> </ul>
<ul class="nav navbar-nav navbar-right"> <ul class="nav navbar-nav navbar-right">
@if (!Context.CurrentUser.IsAuthenticated()) @if (!Context.CurrentUser.IsAuthenticated())
{ {
<li><a href="/login">Admin</a></li> <li><a href="/login">Admin</a></li>
} }
else else
{ {
<li><a href="/logout">Admin Logout</a></li> <li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Admin <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="/admin">Settings</a></li>
<li><a href="#">User Management</a></li>
<li class="divider"></li>
<li><a href="#">Logout</a></li>
</ul>
</li>
} }
@if (Context.Request.Session[SessionKeys.UsernameKey] != null) @if (Context.Request.Session[SessionKeys.UsernameKey] != null)
{ {

View file

@ -6,5 +6,9 @@
{ {
"outputFile": "Content/pace.css", "outputFile": "Content/pace.css",
"inputFile": "Content/pace.scss" "inputFile": "Content/pace.scss"
},
{
"outputFile": "Content/requests.es5.js",
"inputFile": "Content/requests.js"
} }
] ]

View file

@ -10,6 +10,7 @@
<package id="Microsoft.Owin.Host.HttpListener" version="3.0.1" targetFramework="net452" /> <package id="Microsoft.Owin.Host.HttpListener" version="3.0.1" targetFramework="net452" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.0" targetFramework="net46" /> <package id="Microsoft.Owin.Host.SystemWeb" version="3.0.0" targetFramework="net46" />
<package id="Microsoft.Owin.Hosting" version="3.0.1" targetFramework="net452" /> <package id="Microsoft.Owin.Hosting" version="3.0.1" targetFramework="net452" />
<package id="Mono.Posix" version="4.0.0.0" targetFramework="net46" />
<package id="Nancy" version="1.4.3" targetFramework="net452" /> <package id="Nancy" version="1.4.3" targetFramework="net452" />
<package id="Nancy.Authentication.Basic" version="1.4.1" targetFramework="net452" /> <package id="Nancy.Authentication.Basic" version="1.4.1" targetFramework="net452" />
<package id="Nancy.Authentication.Forms" version="1.4.1" targetFramework="net452" /> <package id="Nancy.Authentication.Forms" version="1.4.1" targetFramework="net452" />