Some performance improvements around the new TV stuff

This commit is contained in:
tidusjar 2016-08-04 11:48:05 +01:00
parent 4bccb8fcf0
commit 53f806fc71
4 changed files with 225 additions and 179 deletions

View file

@ -1,177 +1,177 @@
#region Copyright #region Copyright
// /************************************************************************ // /************************************************************************
// Copyright (c) 2016 Jamie Rees // Copyright (c) 2016 Jamie Rees
// File: LoggingHelper.cs // File: LoggingHelper.cs
// Created By: Jamie Rees // Created By: Jamie Rees
// //
// Permission is hereby granted, free of charge, to any person obtaining // Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the // a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including // "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish, // without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to // distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to // permit persons to whom the Software is furnished to do so, subject to
// the following conditions: // the following conditions:
// //
// The above copyright notice and this permission notice shall be // The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software. // included in all copies or substantial portions of the Software.
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/ // ************************************************************************/
#endregion #endregion
using System; using System;
using System.Data; using System.Data;
using Newtonsoft.Json; using Newtonsoft.Json;
using NLog; using NLog;
using NLog.Config; using NLog.Config;
using NLog.Targets; using NLog.Targets;
namespace PlexRequests.Helpers namespace PlexRequests.Helpers
{ {
public static class LoggingHelper public static class LoggingHelper
{ {
public static string DumpJson(this object value) /// <summary>
{ /// WARNING, This method uses up a LOT of memory and can lead to leaks.
var dumpTarget = value; /// </summary>
//if this is a string that contains a JSON object, do a round-trip serialization to format it: /// <param name="value">The value.</param>
var stringValue = value as string; /// <returns></returns>
if (stringValue != null) public static string DumpJson(this object value)
{ {
if (stringValue.Trim().StartsWith("{", StringComparison.Ordinal)) object dumpTarget;
{ //if this is a string that contains a JSON object, do a round-trip serialization to format it:
var obj = JsonConvert.DeserializeObject(stringValue); var stringValue = value as string;
dumpTarget = JsonConvert.SerializeObject(obj, Formatting.Indented); if (stringValue != null)
} {
else dumpTarget = stringValue.Trim().StartsWith("{", StringComparison.Ordinal)
{ ? JsonConvert.SerializeObject(JsonConvert.DeserializeObject(stringValue), Formatting.Indented)
dumpTarget = stringValue; : stringValue;
} }
} else
else {
{ dumpTarget = JsonConvert.SerializeObject(value, Formatting.Indented);
dumpTarget = JsonConvert.SerializeObject(value, Formatting.Indented); }
} return dumpTarget.ToString();
return dumpTarget.ToString(); }
}
public static void ConfigureLogging(string connectionString)
public static void ConfigureLogging(string connectionString) {
{ LogManager.ThrowExceptions = true;
LogManager.ThrowExceptions = true; // Step 1. Create configuration object
// Step 1. Create configuration object var config = new LoggingConfiguration();
var config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
// Step 2. Create targets and add them to the configuration var databaseTarget = new DatabaseTarget
var databaseTarget = new DatabaseTarget {
{ CommandType = CommandType.Text,
CommandType = CommandType.Text, ConnectionString = connectionString,
ConnectionString = connectionString, DBProvider = "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756",
DBProvider = "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756", Name = "database",
Name = "database"
}; };
var messageParam = new DatabaseParameterInfo { Name = "@Message", Layout = "${message}" }; var messageParam = new DatabaseParameterInfo { Name = "@Message", Layout = "${message}" };
var callsiteParam = new DatabaseParameterInfo { Name = "@Callsite", Layout = "${callsite}" }; var callsiteParam = new DatabaseParameterInfo { Name = "@Callsite", Layout = "${callsite}" };
var levelParam = new DatabaseParameterInfo { Name = "@Level", Layout = "${level}" }; var levelParam = new DatabaseParameterInfo { Name = "@Level", Layout = "${level}" };
var dateParam = new DatabaseParameterInfo { Name = "@Date", Layout = "${date}" }; var dateParam = new DatabaseParameterInfo { Name = "@Date", Layout = "${date}" };
var loggerParam = new DatabaseParameterInfo { Name = "@Logger", Layout = "${logger}" }; var loggerParam = new DatabaseParameterInfo { Name = "@Logger", Layout = "${logger}" };
var exceptionParam = new DatabaseParameterInfo { Name = "@Exception", Layout = "${exception:tostring}" }; var exceptionParam = new DatabaseParameterInfo { Name = "@Exception", Layout = "${exception:tostring}" };
databaseTarget.Parameters.Add(messageParam); databaseTarget.Parameters.Add(messageParam);
databaseTarget.Parameters.Add(callsiteParam); databaseTarget.Parameters.Add(callsiteParam);
databaseTarget.Parameters.Add(levelParam); databaseTarget.Parameters.Add(levelParam);
databaseTarget.Parameters.Add(dateParam); databaseTarget.Parameters.Add(dateParam);
databaseTarget.Parameters.Add(loggerParam); databaseTarget.Parameters.Add(loggerParam);
databaseTarget.Parameters.Add(exceptionParam); databaseTarget.Parameters.Add(exceptionParam);
databaseTarget.CommandText = "INSERT INTO Logs (Date,Level,Logger, Message, Callsite, Exception) VALUES(@Date,@Level,@Logger, @Message, @Callsite, @Exception);"; databaseTarget.CommandText = "INSERT INTO Logs (Date,Level,Logger, Message, Callsite, Exception) VALUES(@Date,@Level,@Logger, @Message, @Callsite, @Exception);";
config.AddTarget("database", databaseTarget); config.AddTarget("database", databaseTarget);
// Step 4. Define rules // Step 4. Define rules
var rule1 = new LoggingRule("*", LogLevel.Info, databaseTarget); var rule1 = new LoggingRule("*", LogLevel.Debug, databaseTarget);
config.LoggingRules.Add(rule1); config.LoggingRules.Add(rule1);
var fileTarget = new FileTarget var fileTarget = new FileTarget
{ {
Name = "file", Name = "file",
FileName = "logs/${shortdate}.log", FileName = "logs/${shortdate}.log",
Layout = "${date} ${logger} ${level}: ${message} ${exception:tostring}", Layout = "${date} ${logger} ${level}: ${message} ${exception:tostring}",
CreateDirs = true CreateDirs = true
}; };
config.AddTarget(fileTarget); config.AddTarget(fileTarget);
var rule2 = new LoggingRule("*", LogLevel.Info, fileTarget); var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
config.LoggingRules.Add(rule2); config.LoggingRules.Add(rule2);
// Step 5. Activate the configuration // Step 5. Activate the configuration
LogManager.Configuration = config; LogManager.Configuration = config;
} }
public static void ReconfigureLogLevel(LogLevel level) public static void ReconfigureLogLevel(LogLevel level)
{ {
foreach (var rule in LogManager.Configuration.LoggingRules) foreach (var rule in LogManager.Configuration.LoggingRules)
{ {
// Remove all levels // Remove all levels
rule.DisableLoggingForLevel(LogLevel.Trace); rule.DisableLoggingForLevel(LogLevel.Trace);
rule.DisableLoggingForLevel(LogLevel.Info); rule.DisableLoggingForLevel(LogLevel.Info);
rule.DisableLoggingForLevel(LogLevel.Debug); rule.DisableLoggingForLevel(LogLevel.Debug);
rule.DisableLoggingForLevel(LogLevel.Warn); rule.DisableLoggingForLevel(LogLevel.Warn);
rule.DisableLoggingForLevel(LogLevel.Error); rule.DisableLoggingForLevel(LogLevel.Error);
rule.DisableLoggingForLevel(LogLevel.Fatal); rule.DisableLoggingForLevel(LogLevel.Fatal);
if (level == LogLevel.Trace) if (level == LogLevel.Trace)
{ {
rule.EnableLoggingForLevel(LogLevel.Trace); rule.EnableLoggingForLevel(LogLevel.Trace);
rule.EnableLoggingForLevel(LogLevel.Info); rule.EnableLoggingForLevel(LogLevel.Info);
rule.EnableLoggingForLevel(LogLevel.Debug); rule.EnableLoggingForLevel(LogLevel.Debug);
rule.EnableLoggingForLevel(LogLevel.Warn); rule.EnableLoggingForLevel(LogLevel.Warn);
rule.EnableLoggingForLevel(LogLevel.Error); rule.EnableLoggingForLevel(LogLevel.Error);
rule.EnableLoggingForLevel(LogLevel.Fatal); rule.EnableLoggingForLevel(LogLevel.Fatal);
} }
if (level == LogLevel.Info) if (level == LogLevel.Info)
{ {
rule.EnableLoggingForLevel(LogLevel.Info); rule.EnableLoggingForLevel(LogLevel.Info);
rule.EnableLoggingForLevel(LogLevel.Warn); rule.EnableLoggingForLevel(LogLevel.Warn);
rule.EnableLoggingForLevel(LogLevel.Error); rule.EnableLoggingForLevel(LogLevel.Error);
rule.EnableLoggingForLevel(LogLevel.Fatal); rule.EnableLoggingForLevel(LogLevel.Fatal);
} }
if (level == LogLevel.Debug) if (level == LogLevel.Debug)
{ {
rule.EnableLoggingForLevel(LogLevel.Debug); rule.EnableLoggingForLevel(LogLevel.Debug);
rule.EnableLoggingForLevel(LogLevel.Warn); rule.EnableLoggingForLevel(LogLevel.Warn);
rule.EnableLoggingForLevel(LogLevel.Error); rule.EnableLoggingForLevel(LogLevel.Error);
rule.EnableLoggingForLevel(LogLevel.Fatal); rule.EnableLoggingForLevel(LogLevel.Fatal);
} }
if (level == LogLevel.Warn) if (level == LogLevel.Warn)
{ {
rule.EnableLoggingForLevel(LogLevel.Warn); rule.EnableLoggingForLevel(LogLevel.Warn);
rule.EnableLoggingForLevel(LogLevel.Error); rule.EnableLoggingForLevel(LogLevel.Error);
rule.EnableLoggingForLevel(LogLevel.Fatal); rule.EnableLoggingForLevel(LogLevel.Fatal);
} }
if (level == LogLevel.Error) if (level == LogLevel.Error)
{ {
rule.EnableLoggingForLevel(LogLevel.Error); rule.EnableLoggingForLevel(LogLevel.Error);
rule.EnableLoggingForLevel(LogLevel.Fatal); rule.EnableLoggingForLevel(LogLevel.Fatal);
} }
if (level == LogLevel.Fatal) if (level == LogLevel.Fatal)
{ {
rule.EnableLoggingForLevel(LogLevel.Fatal); rule.EnableLoggingForLevel(LogLevel.Fatal);
} }
} }
//Call to update existing Loggers created with GetLogger() or //Call to update existing Loggers created with GetLogger() or
//GetCurrentClassLogger() //GetCurrentClassLogger()
LogManager.ReconfigExistingLoggers(); LogManager.ReconfigExistingLoggers();
} }
} }
} }

View file

@ -39,5 +39,16 @@ namespace PlexRequests.Services.Interfaces
List<PlexAlbum> GetPlexAlbums(); List<PlexAlbum> GetPlexAlbums();
bool IsAlbumAvailable(PlexAlbum[] plexAlbums, string title, string year, string artist); bool IsAlbumAvailable(PlexAlbum[] plexAlbums, string title, string year, string artist);
bool IsEpisodeAvailable(string theTvDbId, int season, int episode); bool IsEpisodeAvailable(string theTvDbId, int season, int episode);
/// <summary>
/// Gets the episode's stored in the cache.
/// </summary>
/// <returns></returns>
IEnumerable<PlexEpisodeModel> GetEpisodeCache();
/// <summary>
/// Gets the episode's stored in the cache and then filters on the TheTvDBId.
/// </summary>
/// <param name="theTvDbId">The tv database identifier.</param>
/// <returns></returns>
IEnumerable<PlexEpisodeModel> GetEpisodeCache(int theTvDbId);
} }
} }

View file

@ -257,6 +257,38 @@ namespace PlexRequests.Services.Jobs
return false; return false;
} }
/// <summary>
/// Gets the episode's stored in the cache.
/// </summary>
/// <returns></returns>
public IEnumerable<PlexEpisodeModel> GetEpisodeCache()
{
var episodes = Cache.Get<List<PlexEpisodeModel>>(CacheKeys.PlexEpisodes);
if (episodes == null)
{
Log.Info("Episode cache info is not available.");
return new List<PlexEpisodeModel>();
}
return episodes;
}
/// <summary>
/// Gets the episode's stored in the cache and then filters on the TheTvDBId.
/// </summary>
/// <param name="theTvDbId">The tv database identifier.</param>
/// <returns></returns>
public IEnumerable<PlexEpisodeModel> GetEpisodeCache(int theTvDbId)
{
var episodes = Cache.Get<List<PlexEpisodeModel>>(CacheKeys.PlexEpisodes);
if (episodes == null)
{
Log.Info("Episode cache info is not available.");
return new List<PlexEpisodeModel>();
}
return episodes.Where(x => x.Episodes.ProviderId == theTvDbId.ToString());
}
public List<PlexAlbum> GetPlexAlbums() public List<PlexAlbum> GetPlexAlbums()
{ {
var albums = new List<PlexAlbum>(); var albums = new List<PlexAlbum>();

View file

@ -608,9 +608,10 @@ namespace PlexRequests.UI.Modules
} }
if (episodeRequest) if (episodeRequest)
{ {
var cachedEpisodes = Checker.GetEpisodeCache().ToList();
foreach (var d in difference) foreach (var d in difference)
{ {
if (Checker.IsEpisodeAvailable(providerId, d.SeasonNumber, d.EpisodeNumber)) if (cachedEpisodes.Any(x => x.Episodes.SeasonNumber == d.SeasonNumber && x.Episodes.EpisodeNumber == d.EpisodeNumber && x.Episodes.ProviderId == providerId))
{ {
return Response.AsJson(new JsonResponseModel { Result = false, Message = $"{fullShowName} {d.SeasonNumber} - {d.EpisodeNumber} {Resources.UI.Search_AlreadyInPlex}" }); return Response.AsJson(new JsonResponseModel { Result = false, Message = $"{fullShowName} {d.SeasonNumber} - {d.EpisodeNumber} {Resources.UI.Search_AlreadyInPlex}" });
} }
@ -982,13 +983,15 @@ namespace PlexRequests.UI.Modules
sonarrEpisodes = sonarrEp?.ToList() ?? new List<SonarrEpisodes>(); sonarrEpisodes = sonarrEp?.ToList() ?? new List<SonarrEpisodes>();
} }
var plexCache = Checker.GetEpisodeCache(seriesId).ToList();
foreach (var ep in seasons) foreach (var ep in seasons)
{ {
var requested = dbDbShow?.Episodes var requested = dbDbShow?.Episodes
.Any(episodesModel => .Any(episodesModel =>
ep.number == episodesModel.EpisodeNumber && ep.season == episodesModel.SeasonNumber) ?? false; ep.number == episodesModel.EpisodeNumber && ep.season == episodesModel.SeasonNumber) ?? false;
var alreadyInPlex = Checker.IsEpisodeAvailable(seriesId.ToString(), ep.season, ep.number); var alreadyInPlex = plexCache.Any(x => x.Episodes.EpisodeNumber == ep.number && x.Episodes.SeasonNumber == ep.season);
var inSonarr = sonarrEpisodes.Any(x => x.seasonNumber == ep.season && x.episodeNumber == ep.number && x.monitored); var inSonarr = sonarrEpisodes.Any(x => x.seasonNumber == ep.season && x.episodeNumber == ep.number && x.monitored);
model.Add(new EpisodeListViewModel model.Add(new EpisodeListViewModel