Skip to content

Commit

Permalink
Fixed #277
Browse files Browse the repository at this point in the history
  • Loading branch information
tidusjar committed May 27, 2016
1 parent a1ae37e commit 34e74c7
Show file tree
Hide file tree
Showing 6 changed files with 176 additions and 63 deletions.
22 changes: 20 additions & 2 deletions PlexRequests.Core/Setup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public string SetupDb(string urlBase)
{
CreateDefaultSettingsPage(urlBase);
}

var version = CheckSchema();
if (version > 0)
{
Expand All @@ -77,7 +77,7 @@ private int CheckSchema()
{
var productVersion = AssemblyHelper.GetProductVersion();
var trimStatus = new Regex("[^0-9]", RegexOptions.Compiled).Replace(productVersion, string.Empty).PadRight(4, '0');
var version = int.Parse(trimStatus);
var version = int.Parse(trimStatus);

var connection = Db.DbConnection();
var schema = connection.GetSchemaVersion();
Expand Down Expand Up @@ -181,6 +181,7 @@ public void MigrateToVersion1700()
/// <summary>
/// Migrates to version 1.8.
/// <para>This includes updating the admin account to have all roles.</para>
/// <para>Set the log level to info</para>
/// </summary>
private void MigrateToVersion1800()
{
Expand All @@ -203,6 +204,23 @@ private void MigrateToVersion1800()
throw;
}

try
{
var settingsService = new SettingsServiceV2<LogSettings>(new SettingsJsonRepository(Db, new MemoryCacheProvider()));
var logSettings = settingsService.GetSettings();
logSettings.Level = LogLevel.Info.Ordinal;
settingsService.SaveSettings(logSettings);

LoggingHelper.ReconfigureLogLevel(LogLevel.FromOrdinal(logSettings.Level));

}
catch (Exception e)
{
Log.Error(e);
throw;
}


}
}
}
3 changes: 2 additions & 1 deletion PlexRequests.Services/Jobs/JobNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
namespace PlexRequests.Services
namespace PlexRequests.Services.Jobs
{
public static class JobNames
{
Expand All @@ -33,5 +33,6 @@ public static class JobNames
public const string SonarrCacher = "Sonarr Cacher";
public const string SrCacher = "SickRage Cacher";
public const string PlexChecker = "Plex Availability Cacher";
public const string StoreCleanup = "Database Cleanup";
}
}
117 changes: 59 additions & 58 deletions PlexRequests.Services/Jobs/StoreBackup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,11 @@
#endregion
using System;
using System.IO;
using System.Linq;
using System.Globalization;

using NLog;

using PlexRequests.Services.Interfaces;
using PlexRequests.Store;
using PlexRequests.Store.Models;
using PlexRequests.Store.Repository;

using Quartz;

Expand All @@ -57,7 +53,7 @@ public StoreBackup(ISqliteConfiguration sql, IJobRecord rec)
public void Execute(IJobExecutionContext context)
{
TakeBackup();
Cleanup ();
Cleanup();
}

private void TakeBackup()
Expand All @@ -81,11 +77,11 @@ private void TakeBackup()

try
{
if(DoWeNeedToBackup(backupDir.FullName))
{
File.Copy(dbPath, Path.Combine(backupDir.FullName, $"PlexRequests.sqlite_{DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss")}.bak"));
}
}
if (DoWeNeedToBackup(backupDir.FullName))
{
File.Copy(dbPath, Path.Combine(backupDir.FullName, $"PlexRequests.sqlite_{DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss")}.bak"));
}
}
catch (Exception e)
{
Log.Warn(e);
Expand All @@ -98,53 +94,58 @@ private void TakeBackup()

}

private void Cleanup()
{
Log.Trace("Starting DB Cleanup");
var dbPath = Sql.CurrentPath;
var dir = Path.GetDirectoryName(dbPath);
if (dir == null)
{
Log.Warn("We couldn't find the DB path. We cannot backup.");
return;
}
var backupDir = Directory.CreateDirectory(Path.Combine(dir, "Backup"));

var files = backupDir.GetFiles();

foreach (var file in files) {
var dt = ParseName(file.Name);
if(dt < DateTime.Now.AddDays(-7)){
try {

File.Delete(file.FullName);
} catch (Exception ex) {
Log.Error(ex);
}
}
}

}

private bool DoWeNeedToBackup(string backupPath)
{
var files = Directory.GetFiles(backupPath);
//TODO Get the latest file and if it's within an hour of DateTime.Now then don't bother backing up.
return true;
}

private DateTime ParseName(string fileName)
{
var names = fileName.Split(new []{'_','.',' '}, StringSplitOptions.RemoveEmptyEntries);
if(names.Count() > 1)
{
DateTime parsed;
//DateTime.TryParseExcat(names[1], "yyyy-MM-dd hh.mm.ss",CultureInfo.CurrentUICulture, DateTimeStyles.None, out parsed);
DateTime.TryParse(names[2], out parsed);
return parsed;

}
return DateTime.MinValue;
}
private void Cleanup()
{
Log.Trace("Starting DB Cleanup");
var dbPath = Sql.CurrentPath;
var dir = Path.GetDirectoryName(dbPath);
if (dir == null)
{
Log.Warn("We couldn't find the DB path. We cannot backup.");
return;
}
var backupDir = Directory.CreateDirectory(Path.Combine(dir, "Backup"));

var files = backupDir.GetFiles();

foreach (var file in files)
{
var dt = ParseName(file.Name);
if (dt < DateTime.Now.AddDays(-7))
{
try
{

File.Delete(file.FullName);
}
catch (Exception ex)
{
Log.Error(ex);
}
}
}

}

private bool DoWeNeedToBackup(string backupPath)
{
var files = Directory.GetFiles(backupPath);
//TODO Get the latest file and if it's within an hour of DateTime.Now then don't bother backing up.
return true;
}

private DateTime ParseName(string fileName)
{
var names = fileName.Split(new[] { '_', '.', ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (names.Length > 1)
{
DateTime parsed;
//DateTime.TryParseExcat(names[1], "yyyy-MM-dd hh.mm.ss",CultureInfo.CurrentUICulture, DateTimeStyles.None, out parsed);
DateTime.TryParse(names[2], out parsed);
return parsed;

}
return DateTime.MinValue;
}
}
}
82 changes: 82 additions & 0 deletions PlexRequests.Services/Jobs/StoreCleanup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: StoreCleanup.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.Linq;

using NLog;

using PlexRequests.Services.Interfaces;
using PlexRequests.Store.Models;
using PlexRequests.Store.Repository;

using Quartz;

namespace PlexRequests.Services.Jobs
{
public class StoreCleanup : IJob
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();

public StoreCleanup(IRepository<LogEntity> repo, IJobRecord rec)
{
Repo = repo;
JobRecord = rec;
}

private IJobRecord JobRecord { get; }

private IRepository<LogEntity> Repo { get; }

private void Cleanup()
{
try
{
var items = Repo.GetAll();
var orderedItems = items.Where(x => x.Date < DateTime.Now.AddDays(-7));

foreach (var o in orderedItems)
{
Repo.Delete(o);
}
}
catch (Exception e)
{
Log.Error(e);
}
finally
{
JobRecord.Record(JobNames.StoreCleanup);
}

}

public void Execute(IJobExecutionContext context)
{
Cleanup();
}
}
}
1 change: 1 addition & 0 deletions PlexRequests.Services/PlexRequests.Services.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
<Compile Include="Jobs\JobRecord.cs" />
<Compile Include="Jobs\JobNames.cs" />
<Compile Include="Jobs\StoreBackup.cs" />
<Compile Include="Jobs\StoreCleanup.cs" />
<Compile Include="Jobs\CouchPotatoCacher.cs" />
<Compile Include="Jobs\PlexAvailabilityChecker.cs" />
<Compile Include="Jobs\SickRageCacher.cs" />
Expand Down
14 changes: 12 additions & 2 deletions PlexRequests.UI/Jobs/Scheduler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,15 @@ private IEnumerable<IJobDetail> CreateJobs()
var sickrage = JobBuilder.Create<SickRageCacher>().WithIdentity("SickRageCacher", "Cache").Build();
var sonarr = JobBuilder.Create<SonarrCacher>().WithIdentity("SonarrCacher", "Cache").Build();
var cp = JobBuilder.Create<CouchPotatoCacher>().WithIdentity("CouchPotatoCacher", "Cache").Build();
var store = JobBuilder.Create<StoreBackup>().WithIdentity("StoreBackup", "Backup").Build();
var store = JobBuilder.Create<StoreBackup>().WithIdentity("StoreBackup", "Database").Build();
var storeClean = JobBuilder.Create<StoreCleanup>().WithIdentity("StoreCleanup", "Database").Build();

jobs.Add(plex);
jobs.Add(sickrage);
jobs.Add(sonarr);
jobs.Add(cp);
jobs.Add(store);
jobs.Add(storeClean);

return jobs;
}
Expand Down Expand Up @@ -129,17 +131,25 @@ private IEnumerable<ITrigger> CreateTriggers()

var storeBackup =
TriggerBuilder.Create()
.WithIdentity("StoreBackup", "Backup")
.WithIdentity("StoreBackup", "Database")
.StartNow()
.WithSimpleSchedule(x => x.WithIntervalInHours(24).RepeatForever())
.Build();

var storeCleanup =
TriggerBuilder.Create()
.WithIdentity("StoreCleanup", "Database")
.StartNow()
.WithSimpleSchedule(x => x.WithIntervalInHours(24).RepeatForever())
.Build();


triggers.Add(plexAvailabilityChecker);
triggers.Add(srCacher);
triggers.Add(sonarrCacher);
triggers.Add(cpCacher);
triggers.Add(storeBackup);
triggers.Add(storeCleanup);

return triggers;
}
Expand Down

0 comments on commit 34e74c7

Please sign in to comment.