Compare commits
27 Commits
0.0.3-alph
...
66716a9bc9
| Author | SHA1 | Date | |
|---|---|---|---|
| 66716a9bc9 | |||
| 9bddc59fe2 | |||
| 82441d5247 | |||
| 4fc8b4799d | |||
| 9e324f14a7 | |||
| d024035d07 | |||
| 8d85194df5 | |||
| d78d1069b1 | |||
| f7c463aba4 | |||
| 77f2873180 | |||
| b2da7beb00 | |||
| 9696826406 | |||
| 873b29985c | |||
| 30107010b1 | |||
| 5af49eb390 | |||
| ee44dd9ee6 | |||
| 9604289684 | |||
| ddf84b5cb6 | |||
| ca1d1fcab1 | |||
| 3b43d6807a | |||
| 2c91846d81 | |||
| c533eb4f90 | |||
| 2fdbae74e8 | |||
| 08e26943c9 | |||
| 65dd638b09 | |||
| 6b20bc0828 | |||
| db3a06cc67 |
@@ -1,5 +1,5 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<AssemblyVersion>0.0.0.3</AssemblyVersion>
|
||||
<AssemblyVersion>0.0.0.10</AssemblyVersion>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
|
||||
@@ -31,4 +31,9 @@ public class PluginConfiguration : BasePluginConfiguration
|
||||
/// Gets or sets the cut off days before deleting unwatched files.
|
||||
/// </summary>
|
||||
public int StaleMediaCutoff { get; set; } = 90;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets debug mode.
|
||||
/// </summary>
|
||||
public bool DebugMode { get; set; }
|
||||
}
|
||||
|
||||
@@ -24,6 +24,12 @@
|
||||
<input id="StaleMediaCutoff" name="StaleMediaCutoff" type="number" is="emby-input" style="width: 20%;"/>
|
||||
<div class="fieldDescription">How many days to wait before marking files as stale</div>
|
||||
</div>
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label class="emby-checkbox-label">
|
||||
<input id="DebugMode" name="DebugMode" type="checkbox" is="emby-checkbox" />
|
||||
<span>Debug Mode</span>
|
||||
</label>
|
||||
</div>
|
||||
<!-- <div class="selectContainer">
|
||||
<label class="selectLabel" for="Options">Several Options</label>
|
||||
<select is="emby-select" id="Options" name="Options" class="emby-select-withcolor emby-select">
|
||||
@@ -71,6 +77,7 @@
|
||||
document.querySelector('#RadarrAPIKey').value = config.RadarrAPIKey;
|
||||
document.querySelector('#SonarrAPIKey').value = config.SonarrAPIKey;
|
||||
document.querySelector('#StaleMediaCutoff').value = config.StaleMediaCutoff;
|
||||
document.querySelector('#DebugMode').checked = config.DebugMode;
|
||||
Dashboard.hideLoadingMsg();
|
||||
});
|
||||
});
|
||||
@@ -86,6 +93,7 @@
|
||||
config.RadarrAPIKey = document.querySelector('#RadarrAPIKey').value;
|
||||
config.SonarrAPIKey = document.querySelector('#SonarrAPIKey').value;
|
||||
config.StaleMediaCutoff = document.querySelector('#StaleMediaCutoff').value;
|
||||
config.DebugMode = document.querySelector('#DebugMode').checked;
|
||||
ApiClient.updatePluginConfiguration(MediaCleanerConfig.pluginUniqueId, config).then(function (result) {
|
||||
Dashboard.processPluginConfigurationUpdateResult(result);
|
||||
});
|
||||
|
||||
22
Jellyfin.Plugin.MediaCleaner/Controllers/StateController.cs
Normal file
22
Jellyfin.Plugin.MediaCleaner/Controllers/StateController.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using Jellyfin.Plugin.MediaCleaner.Data;
|
||||
using Jellyfin.Plugin.MediaCleaner.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Jellyfin.Plugin.MediaCleaner.Controllers;
|
||||
|
||||
[Route("mediacleaner/state")]
|
||||
public class StateController : Controller
|
||||
{
|
||||
private readonly PluginState _state;
|
||||
public StateController(PluginState state) => _state = state;
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult Get() => Ok(_state.GetSeriesInfo());
|
||||
|
||||
[HttpPost("add")]
|
||||
public IActionResult AddSeriesInfo([FromBody] SeriesInfo seriesInfo)
|
||||
{
|
||||
_state.AddSeriesInfo(seriesInfo);
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
29
Jellyfin.Plugin.MediaCleaner/Data/PluginState.cs
Normal file
29
Jellyfin.Plugin.MediaCleaner/Data/PluginState.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System.Collections.Generic;
|
||||
using Jellyfin.Plugin.MediaCleaner.Models;
|
||||
|
||||
namespace Jellyfin.Plugin.MediaCleaner.Data;
|
||||
|
||||
public class PluginState
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
private List<SeriesInfo> _seriesInfo = new List<SeriesInfo>
|
||||
{
|
||||
new SeriesInfo { SeriesName = "TestName", Id = System.Guid.NewGuid() }
|
||||
};
|
||||
|
||||
public void AddSeriesInfo(SeriesInfo seriesInfo)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_seriesInfo.Add(seriesInfo);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<SeriesInfo> GetSeriesInfo()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _seriesInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
35
Jellyfin.Plugin.MediaCleaner/Helpers/LoggingHelper.cs
Normal file
35
Jellyfin.Plugin.MediaCleaner/Helpers/LoggingHelper.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Jellyfin.Plugin.MediaCleaner.Configuration;
|
||||
using Jellyfin.Plugin.MediaCleaner.Models;
|
||||
using Jellyfin.Plugin.MediaCleaner.ScheduledTasks;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.MediaCleaner.Helpers;
|
||||
|
||||
public class LoggingHelper(ILogger logger)
|
||||
{
|
||||
private readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
[SuppressMessage("Microsoft.Performance", "CA2254:TemplateShouldBeConstant", Justification = "Message parameter is intentionally variable for flexible debug logging")]
|
||||
public void LogDebugInformation(string message, params object?[] args)
|
||||
{
|
||||
if (Configuration.DebugMode)
|
||||
{
|
||||
_logger.LogInformation(message, args);
|
||||
}
|
||||
}
|
||||
|
||||
[SuppressMessage("Microsoft.Performance", "CA2254:TemplateShouldBeConstant", Justification = "Message parameter is intentionally variable for flexible logging")]
|
||||
public void LogInformation(string message, params object?[] args)
|
||||
{
|
||||
_logger.LogInformation(message, args);
|
||||
}
|
||||
|
||||
private static PluginConfiguration Configuration =>
|
||||
Plugin.Instance!.Configuration;
|
||||
}
|
||||
73
Jellyfin.Plugin.MediaCleaner/Helpers/MovieHelper.cs
Normal file
73
Jellyfin.Plugin.MediaCleaner/Helpers/MovieHelper.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Jellyfin.Database.Implementations.Entities;
|
||||
using Jellyfin.Plugin.MediaCleaner.Configuration;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.MediaCleaner.Helpers;
|
||||
|
||||
public class MovieHelper(ILogger logger)
|
||||
{
|
||||
private readonly LoggingHelper _loggingHelper = new(logger);
|
||||
|
||||
private static PluginConfiguration Configuration =>
|
||||
Plugin.Instance!.Configuration;
|
||||
|
||||
public bool IsMovieStale(BaseItem movie)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(movie, "IsMovieStale process recieved a null movie. Logic failure. Exception thrown.");
|
||||
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogDebugInformation("Scanning movie: {Movie}", movie);
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
|
||||
bool movieIsStale = false;
|
||||
|
||||
bool createdOutsideCutoff = movie.DateCreated < DateTime.Now.AddDays(-Configuration.StaleMediaCutoff);
|
||||
bool hasUserData = movie.UserData.Where(data => data.LastPlayedDate != null).ToList().Count > 0;
|
||||
|
||||
if (hasUserData)
|
||||
{
|
||||
var mostRecentUserData = movie.UserData.OrderByDescending(data => data.LastPlayedDate).First(data => data.LastPlayedDate != null);
|
||||
|
||||
_loggingHelper.LogDebugInformation("Most recent user data: {Movie}", movie);
|
||||
|
||||
foreach (var property in typeof(UserData).GetProperties())
|
||||
{
|
||||
_loggingHelper.LogDebugInformation("{PropertyName}: {PropertyValue}", property.Name, property.GetValue(mostRecentUserData));
|
||||
}
|
||||
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
|
||||
if (mostRecentUserData.LastPlayedDate < DateTime.Now.AddDays(-Configuration.StaleMediaCutoff))
|
||||
{
|
||||
_loggingHelper.LogDebugInformation("Most recent user data has last played date that is outside of cutoff.");
|
||||
_loggingHelper.LogDebugInformation("Adding {Movie} to stale movies.", movie);
|
||||
_loggingHelper.LogDebugInformation("With Last Played Date: {LastPlayedDate}", mostRecentUserData.LastPlayedDate);
|
||||
|
||||
movieIsStale = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (createdOutsideCutoff && !hasUserData)
|
||||
{
|
||||
_loggingHelper.LogDebugInformation("Movie has no user data and was created outside of cutoff: {DateCreated}.", movie.DateCreated);
|
||||
_loggingHelper.LogDebugInformation("Adding {Movie} to stale movies.", movie);
|
||||
movieIsStale = true;
|
||||
}
|
||||
|
||||
if (!createdOutsideCutoff && !hasUserData)
|
||||
{
|
||||
_loggingHelper.LogDebugInformation("Movie has no user data and was not created outside of cutoff: {DateCreated}.", movie.DateCreated);
|
||||
_loggingHelper.LogDebugInformation("Movie is not stale.");
|
||||
}
|
||||
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogDebugInformation("End of scanning for movie: {Movie}", movie);
|
||||
|
||||
return movieIsStale;
|
||||
}
|
||||
|
||||
}
|
||||
89
Jellyfin.Plugin.MediaCleaner/Helpers/SeriesHelper.cs
Normal file
89
Jellyfin.Plugin.MediaCleaner/Helpers/SeriesHelper.cs
Normal file
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Jellyfin.Database.Implementations.Entities;
|
||||
using Jellyfin.Database.Implementations.Entities.Libraries;
|
||||
using Jellyfin.Plugin.MediaCleaner.Configuration;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
|
||||
namespace Jellyfin.Plugin.MediaCleaner.Helpers;
|
||||
|
||||
public class SeriesHelper(ILogger logger)
|
||||
{
|
||||
private readonly LoggingHelper _loggingHelper = new(logger);
|
||||
|
||||
private static PluginConfiguration Configuration =>
|
||||
Plugin.Instance!.Configuration;
|
||||
|
||||
private List<BaseItem> ProcessEpisodes(IReadOnlyCollection<BaseItem> episodes)
|
||||
{
|
||||
List<BaseItem> staleEpisodes = [.. episodes
|
||||
.Where(episode =>
|
||||
{
|
||||
bool episodeIsStale = false;
|
||||
|
||||
var staleCreationDate = episode.DateCreated < DateTime.Now.AddDays(-Configuration.StaleMediaCutoff);
|
||||
var hasUserDataWithLastPlayedDate = episode.UserData.Any(data => data.LastPlayedDate != null);
|
||||
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogDebugInformation("Debug data for episode: {Episode}", episode);
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
|
||||
if (staleCreationDate && !hasUserDataWithLastPlayedDate){
|
||||
_loggingHelper.LogDebugInformation("Creation date is stale, and no user data for episode {Episode}.", episode);
|
||||
_loggingHelper.LogDebugInformation("Date created: {DateCreated}", episode.DateCreated);
|
||||
episodeIsStale = true;
|
||||
}
|
||||
|
||||
if (hasUserDataWithLastPlayedDate){
|
||||
UserData mostRecentUserData = episode.UserData
|
||||
.OrderByDescending(data => data.LastPlayedDate)
|
||||
.First();
|
||||
|
||||
foreach (var property in typeof(UserData).GetProperties())
|
||||
{
|
||||
_loggingHelper.LogDebugInformation("{PropertyName}: {PropertyValue}", property.Name, property.GetValue(mostRecentUserData));
|
||||
}
|
||||
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
|
||||
bool staleLastPlayedDate = mostRecentUserData.LastPlayedDate < DateTime.Now.AddDays(-Configuration.StaleMediaCutoff);
|
||||
|
||||
if (staleLastPlayedDate && staleCreationDate)
|
||||
{
|
||||
episodeIsStale = true;
|
||||
_loggingHelper.LogDebugInformation("Most recent user data has a last played date of: {LastPlayedDate}.", [mostRecentUserData.LastPlayedDate]);
|
||||
_loggingHelper.LogDebugInformation("Episode created {DateCreated}.", episode.DateCreated);
|
||||
_loggingHelper.LogDebugInformation("Episode is marked as stale.");
|
||||
}
|
||||
}
|
||||
|
||||
return episodeIsStale;
|
||||
})];
|
||||
|
||||
return staleEpisodes;
|
||||
}
|
||||
|
||||
public bool IsSeasonDataStale(IReadOnlyList<BaseItem> episodes)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(episodes, "IsSeasonDataStale process recieved null episodes. Logic failure. Exception thrown.");
|
||||
|
||||
bool seasonIsStale = false;
|
||||
|
||||
List<BaseItem> staleEpisodes = ProcessEpisodes(episodes);
|
||||
|
||||
if(staleEpisodes.Count == episodes.Count)
|
||||
{
|
||||
seasonIsStale = true;
|
||||
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogDebugInformation("Stale episodes count matches season episode count. Season is stale.");
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
}
|
||||
|
||||
return seasonIsStale;
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,8 @@
|
||||
<ItemGroup>
|
||||
<None Remove="Configuration\settings.html" />
|
||||
<EmbeddedResource Include="Configuration\settings.html" />
|
||||
<None Remove="Pages\home.html" />
|
||||
<EmbeddedResource Include="Pages\home.html" />
|
||||
<None Remove="Pages\*" />
|
||||
<EmbeddedResource Include="Pages\*" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
|
||||
@@ -22,9 +22,5 @@ public class SeriesInfo
|
||||
/// <summary>
|
||||
/// Gets or sets seasons.
|
||||
/// </summary>
|
||||
#pragma warning disable CA2227 // Collection properties should be read only
|
||||
#pragma warning disable CA1002 // Do not expose generic lists
|
||||
public List<string> Seasons { get; set; } = [];
|
||||
#pragma warning restore CA1002 // Do not expose generic lists
|
||||
#pragma warning restore CA2227 // Collection properties should be read only
|
||||
public IEnumerable<string> Seasons { get; set; } = [];
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<div data-role="page" class="page type-interior pluginConfigurationPage withTabs">
|
||||
<div data-role="page" class="page type-interior pluginConfigurationPage withTabs"
|
||||
data-controller="__plugin/media_cleaner_table.js">
|
||||
<div data-role="content">
|
||||
<div class="content-primary">
|
||||
<div>
|
||||
@@ -6,6 +7,15 @@
|
||||
<a href="#configurationpage?name=Settings">Settings</a>
|
||||
</div>
|
||||
<h2>Media Cleaner</h2>
|
||||
<table id="seriesTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Series Name</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
27
Jellyfin.Plugin.MediaCleaner/Pages/media_cleaner_table.js
Normal file
27
Jellyfin.Plugin.MediaCleaner/Pages/media_cleaner_table.js
Normal file
@@ -0,0 +1,27 @@
|
||||
var table = document.getElementById("seriesTable");
|
||||
|
||||
|
||||
|
||||
const getMediaCleanerState = async () => {
|
||||
const response = await fetch('/mediacleaner/state');
|
||||
|
||||
if(!response.ok){
|
||||
throw new Error(`Response status: ${response.status}`)
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
var state = await getMediaCleanerState();
|
||||
|
||||
console.log("State: ", state);
|
||||
|
||||
for(let i = 0; i < state.length; i++){
|
||||
var row = table.insertRow(-1);
|
||||
var cell1 = row.insertCell(0);
|
||||
var cell2 = row.insertCell(1);
|
||||
var cell3 = row.insertCell(2);
|
||||
cell1.innerHTML = state[i].Id;
|
||||
cell2.innerHTML = state[i].SeriesName;
|
||||
cell3.innerHTML = state[i].Seasons.length;
|
||||
}
|
||||
@@ -2,11 +2,13 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Jellyfin.Plugin.MediaCleaner.Configuration;
|
||||
using Jellyfin.Plugin.MediaCleaner.Data;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Common.Plugins;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Model.Plugins;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Jellyfin.Plugin.MediaCleaner;
|
||||
|
||||
@@ -53,6 +55,11 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
|
||||
EmbeddedResourcePath = string.Format(CultureInfo.InvariantCulture, "{0}.Pages.home.html", GetType().Namespace),
|
||||
EnableInMainMenu = true,
|
||||
},
|
||||
new PluginPageInfo
|
||||
{
|
||||
Name = "media_cleaner_table.js",
|
||||
EmbeddedResourcePath = string.Format(CultureInfo.InvariantCulture, "{0}.Pages.media_cleaner_table.js", GetType().Namespace),
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
13
Jellyfin.Plugin.MediaCleaner/PluginServiceRegistrator.cs
Normal file
13
Jellyfin.Plugin.MediaCleaner/PluginServiceRegistrator.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using Jellyfin.Plugin.MediaCleaner.Data;
|
||||
using MediaBrowser.Controller;
|
||||
using MediaBrowser.Controller.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Jellyfin.Plugin.MediaCleaner;
|
||||
public class PluginServiceRegistrator : IPluginServiceRegistrator
|
||||
{
|
||||
public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost)
|
||||
{
|
||||
serviceCollection.AddSingleton<PluginState>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
#pragma warning disable RS0030 // Do not use banned APIs
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Database.Implementations;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
using MediaBrowser.Model.Tasks;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.MediaCleaner.ScheduledTasks;
|
||||
|
||||
/// <summary>
|
||||
/// Task to clean up any detached userdata from the database.
|
||||
/// </summary>
|
||||
public class CleanupUserDataTask : IScheduledTask
|
||||
{
|
||||
private readonly ILocalizationManager _localization;
|
||||
private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
|
||||
private readonly ILogger<CleanupUserDataTask> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CleanupUserDataTask"/> class.
|
||||
/// </summary>
|
||||
/// <param name="localization">The localisation Provider.</param>
|
||||
/// <param name="dbProvider">The DB context factory.</param>
|
||||
/// <param name="logger">A logger.</param>
|
||||
public CleanupUserDataTask(ILocalizationManager localization, IDbContextFactory<JellyfinDbContext> dbProvider, ILogger<CleanupUserDataTask> logger)
|
||||
{
|
||||
_localization = localization;
|
||||
_dbProvider = dbProvider;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => _localization.GetLocalizedString("CleanupUserDataTask");
|
||||
|
||||
public Guid PlaceholderId => new("00000000-0000-0000-0000-000000000001");
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Description => _localization.GetLocalizedString("CleanupUserDataTaskDescription");
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Category => _localization.GetLocalizedString("Media");
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => nameof(CleanupUserDataTask);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var dbContext = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using (dbContext.ConfigureAwait(false))
|
||||
{
|
||||
var detachedUserData = dbContext.UserData.Where(e => e.ItemId == PlaceholderId);
|
||||
_logger.LogInformation("Deleting {DetachedUserDataCount} detached UserData entries.", detachedUserData.Count());
|
||||
|
||||
await detachedUserData.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Reflection.Metadata.Ecma335;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -11,6 +13,7 @@ using Jellyfin.Data.Enums;
|
||||
using Jellyfin.Database.Implementations.Entities;
|
||||
using Jellyfin.Database.Implementations.Entities.Libraries;
|
||||
using Jellyfin.Plugin.MediaCleaner.Configuration;
|
||||
using Jellyfin.Plugin.MediaCleaner.Helpers;
|
||||
using Jellyfin.Plugin.MediaCleaner.Models;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Library;
|
||||
@@ -25,20 +28,23 @@ namespace Jellyfin.Plugin.MediaCleaner.ScheduledTasks;
|
||||
public sealed class StaleMediaTask : IScheduledTask
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly IUserManager _userManager;
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly LoggingHelper _loggingHelper;
|
||||
private readonly MovieHelper _movieHelper;
|
||||
private readonly SeriesHelper _seriesHelper;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StaleMediaTask"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger.</param>
|
||||
/// <param name="userManager">User manager.</param>
|
||||
/// <param name="libraryManager">.</param>
|
||||
public StaleMediaTask(ILogger<StaleMediaTask> logger, IUserManager userManager, ILibraryManager libraryManager)
|
||||
/// <param name="logger">Logger for StaleMediaTask.</param>
|
||||
/// <param name="libraryManager">Accesses jellyfin's library manager for media.</param>
|
||||
public StaleMediaTask(ILogger<StaleMediaTask> logger, ILibraryManager libraryManager)
|
||||
{
|
||||
_logger = logger;
|
||||
_userManager = userManager;
|
||||
_libraryManager = libraryManager;
|
||||
_loggingHelper = new LoggingHelper(_logger);
|
||||
_movieHelper = new MovieHelper(_logger);
|
||||
_seriesHelper = new SeriesHelper(_logger);
|
||||
}
|
||||
|
||||
private static PluginConfiguration Configuration =>
|
||||
@@ -54,38 +60,76 @@ public sealed class StaleMediaTask : IScheduledTask
|
||||
|
||||
Task IScheduledTask.ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
|
||||
{
|
||||
_loggingHelper.LogDebugInformation("--DEBUG MODE ACTIVE--");
|
||||
_loggingHelper.LogInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogInformation("Starting stale media scan...");
|
||||
_loggingHelper.LogInformation("-------------------------------------------------");
|
||||
|
||||
var query = new InternalItemsQuery
|
||||
{
|
||||
IncludeItemTypes = [BaseItemKind.Movie, BaseItemKind.Series],
|
||||
Recursive = true
|
||||
};
|
||||
|
||||
List<BaseItem> allItems = [.. _libraryManager.GetItemsResult(query).Items];
|
||||
|
||||
_logger.LogInformation("Total items found: {AllItems}", allItems);
|
||||
_loggingHelper.LogInformation("Total items to scan: {ItemCount}", allItems.Count);
|
||||
_loggingHelper.LogDebugInformation("Items found: {AllItems}", allItems);
|
||||
|
||||
List<BaseItem> series = [.. allItems.Where(item => item.GetBaseItemKind() == BaseItemKind.Series)];
|
||||
List<BaseItem> movies = [.. allItems.Where(item => item.GetBaseItemKind() == BaseItemKind.Movie && item.UserData.Count > 0)];
|
||||
List<BaseItem> movies = [.. allItems.Where(item => item.GetBaseItemKind() == BaseItemKind.Movie)];
|
||||
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogDebugInformation("Starting scan of series items.");
|
||||
|
||||
List<BaseItem> staleSeasons = [.. series.SelectMany(GetStaleSeasons)];
|
||||
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogDebugInformation("End of scan for series items.");
|
||||
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogDebugInformation("Starting scan of movie items.");
|
||||
|
||||
List<BaseItem> staleEpisodes = [.. series.SelectMany(GetStaleEpisodes)];
|
||||
List<BaseItem> staleMovies = [.. GetStaleMovies(movies)];
|
||||
|
||||
_logger.LogInformation("Stale Movies found: {StaleMovies}", staleMovies.Count);
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogDebugInformation("End of scan for movie items.");
|
||||
|
||||
_loggingHelper.LogInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogInformation("Stale seasons found: {StaleSeasons}", staleSeasons.Count);
|
||||
|
||||
if (staleSeasons.Count > 0)
|
||||
{
|
||||
IEnumerable<SeriesInfo> staleSeriesInfo = FindSeriesInfo(staleSeasons);
|
||||
|
||||
foreach (var seriesInfo in staleSeriesInfo)
|
||||
{
|
||||
_loggingHelper.LogInformation("Series Info: ID: {Id} | Series Name: {SeriesName} | Stale Seasons: {Seasons}", [seriesInfo.Id, seriesInfo.SeriesName, string.Join(", ", seriesInfo.Seasons)]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_loggingHelper.LogInformation("No stale seasons found!");
|
||||
}
|
||||
|
||||
_loggingHelper.LogInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogInformation("Stale Movies found: {StaleMovies}", staleMovies.Count);
|
||||
|
||||
if (staleMovies.Count > 0)
|
||||
{
|
||||
_logger.LogInformation("Movies: {Names}", string.Join(", ", staleMovies.Select(movie => movie.Name)));
|
||||
foreach (var movieInfo in staleMovies)
|
||||
{
|
||||
_loggingHelper.LogInformation("Movie Info: ID: {Id} | Movie Name: {MovieName}", [movieInfo.Id, movieInfo.Name]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_loggingHelper.LogInformation("No stale movies found!");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Stale Episodes found: {StaleEpisodes}", staleEpisodes.Count);
|
||||
if (staleEpisodes.Count > 0)
|
||||
{
|
||||
// Firstly figure out the seasons, and then the Series to find the name.
|
||||
List<SeriesInfo> seriesInfoList = FindSeriesInfoFromEpisodes(staleEpisodes);
|
||||
|
||||
foreach (var seriesInfo in seriesInfoList)
|
||||
{
|
||||
_logger.LogInformation("Series Info: ID: {Id} | Series Name: {SeriesName} | Stale Seasons: {Seasons}", [seriesInfo.Id, seriesInfo.SeriesName, string.Join(", ", seriesInfo.Seasons)]);
|
||||
}
|
||||
}
|
||||
_loggingHelper.LogInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogInformation("Ending stale media scan...");
|
||||
_loggingHelper.LogInformation("-------------------------------------------------");
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
@@ -94,107 +138,92 @@ public sealed class StaleMediaTask : IScheduledTask
|
||||
{
|
||||
List<BaseItem> staleMovies = [];
|
||||
|
||||
foreach (var movie in movies)
|
||||
try
|
||||
{
|
||||
bool movieIsStale = movie.DateCreated > DateTime.Now.AddDays(-Configuration.StaleMediaCutoff);
|
||||
var mostRecentUserData = movie.UserData.OrderByDescending(data => data.LastPlayedDate).First();
|
||||
|
||||
if (mostRecentUserData.LastPlayedDate < DateTime.Now.AddDays(-Configuration.StaleMediaCutoff))
|
||||
{
|
||||
staleMovies.Add(movie);
|
||||
staleMovies.AddRange(movies.Where(_movieHelper.IsMovieStale));
|
||||
}
|
||||
else if (movieIsStale)
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
staleMovies.Add(movie);
|
||||
}
|
||||
_loggingHelper.LogInformation("Arguement Null Exception in GetStaleMovies!");
|
||||
_loggingHelper.LogInformation(ex.Message);
|
||||
}
|
||||
|
||||
return staleMovies;
|
||||
}
|
||||
|
||||
private List<SeriesInfo> FindSeriesInfoFromEpisodes(List<BaseItem> episodes)
|
||||
|
||||
private List<BaseItem> GetStaleSeasons(BaseItem item)
|
||||
{
|
||||
Guid[] seasonIds = [.. episodes.Select(episode => episode.ParentId).Distinct()];
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogDebugInformation("Debug data for series: {SeriesName}", item.Name);
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
|
||||
var seasons = _libraryManager.GetItemList(new InternalItemsQuery
|
||||
{
|
||||
ItemIds = seasonIds
|
||||
});
|
||||
|
||||
Guid[] seriesIds = [.. seasons.Select(season => season.ParentId).Distinct()];
|
||||
|
||||
var series = _libraryManager.GetItemList(new InternalItemsQuery
|
||||
{
|
||||
ItemIds = seriesIds
|
||||
}).ToList();
|
||||
|
||||
// Series Id, Series Name and Stale Seasons
|
||||
List<string> seriesNames = [.. series.Select(series => series.Name).Distinct()];
|
||||
|
||||
List<SeriesInfo> seriesInfoList = [];
|
||||
|
||||
series.ForEach(series =>
|
||||
{
|
||||
seriesInfoList.Add(new SeriesInfo
|
||||
{
|
||||
Id = series.Id,
|
||||
SeriesName = series.Name,
|
||||
Seasons = [.. seasons.Where(season => season.ParentId == series.Id).Select(season => season.Name)]
|
||||
});
|
||||
});
|
||||
|
||||
return seriesInfoList;
|
||||
}
|
||||
|
||||
private List<BaseItem> GetStaleEpisodes(BaseItem item)
|
||||
{
|
||||
List<BaseItem> staleEpisodes = [];
|
||||
|
||||
// Gets each season in a show
|
||||
var seasons = _libraryManager.GetItemList(new InternalItemsQuery
|
||||
{
|
||||
ParentId = item.Id,
|
||||
Recursive = false
|
||||
});
|
||||
|
||||
foreach (var season in seasons)
|
||||
{
|
||||
// Gets each episode, to access user data.
|
||||
List<BaseItem> staleSeasons = [ ..seasons
|
||||
.Where(season => {
|
||||
var episodes = _libraryManager.GetItemList(new InternalItemsQuery
|
||||
{
|
||||
ParentId = season.Id,
|
||||
Recursive = false
|
||||
});
|
||||
|
||||
bool seasonHasUserData = episodes.Any(episode => episode.UserData.Count > 0);
|
||||
bool seasonIsStale = episodes.All(episode => episode.DateCreated > DateTime.Now.AddDays(-Configuration.StaleMediaCutoff));
|
||||
_loggingHelper.LogDebugInformation("Season debug information for {SeasonNumber}:", season);
|
||||
|
||||
if (seasonHasUserData)
|
||||
bool isSeasonDataStale = false;
|
||||
|
||||
try
|
||||
{
|
||||
var episodesWithUserData = episodes.Where(episode => episode.UserData.Count > 0).ToList();
|
||||
foreach (var episode in episodesWithUserData)
|
||||
isSeasonDataStale = _seriesHelper.IsSeasonDataStale(episodes);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
var mostRecentUserData = episode.UserData.OrderByDescending(data => data.LastPlayedDate).First();
|
||||
if (mostRecentUserData.LastPlayedDate < DateTime.Now.AddDays(-Configuration.StaleMediaCutoff))
|
||||
{
|
||||
staleEpisodes.AddRange(episodes);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check for episodes that have gone unwatched for stale media cutoff
|
||||
else if (seasonIsStale)
|
||||
{
|
||||
staleEpisodes.AddRange(episodes);
|
||||
}
|
||||
_loggingHelper.LogInformation("Arguement Null Exception in GetStaleSeasons!");
|
||||
_loggingHelper.LogInformation(ex.Message);
|
||||
}
|
||||
|
||||
return staleEpisodes;
|
||||
_loggingHelper.LogDebugInformation("End of season debug information for {SeasonNumber}.", season);
|
||||
|
||||
return isSeasonDataStale;
|
||||
})];
|
||||
|
||||
|
||||
_loggingHelper.LogDebugInformation("-------------------------------------------------");
|
||||
_loggingHelper.LogDebugInformation("End of scanning for series: {Series}", item);
|
||||
|
||||
return staleSeasons;
|
||||
}
|
||||
|
||||
private IEnumerable<SeriesInfo> FindSeriesInfo(IReadOnlyCollection<BaseItem> seasons)
|
||||
{
|
||||
Guid[] seriesIds = [.. seasons.Select(season => season.ParentId).Distinct()];
|
||||
|
||||
IReadOnlyCollection<BaseItem> series = _libraryManager.GetItemList(new InternalItemsQuery
|
||||
{
|
||||
ItemIds = seriesIds
|
||||
});
|
||||
|
||||
IEnumerable<SeriesInfo> seriesInfoList = series.Select(series =>
|
||||
{
|
||||
return new SeriesInfo
|
||||
{
|
||||
Id = series.Id,
|
||||
SeriesName = series.Name,
|
||||
Seasons = [.. seasons.Where(season => season.ParentId == series.Id).Select(season => season.Name)]
|
||||
};
|
||||
});
|
||||
|
||||
return seriesInfoList;
|
||||
}
|
||||
|
||||
IEnumerable<TaskTriggerInfo> IScheduledTask.GetDefaultTriggers()
|
||||
{
|
||||
// Run this task every 24 hours
|
||||
// Unnecessary, and will be removed once front end page is ready.
|
||||
yield return new TaskTriggerInfo
|
||||
{
|
||||
Type = TaskTriggerInfoType.IntervalTrigger,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
The idea behind this plugin is to have an easy way to run a task to find all movies and shows in your media collection that users haven't viewed in a number of cutoff days.
|
||||
|
||||
At the time of writing, the plugin is only capable of logging movies and shows that are stale (Unwatched for 90 days) by running a scheduled task. You will need to view your logs to know the number of stale files.
|
||||
At the time of writing, the plugin is only capable of logging movies and shows that are stale (Unwatched for a user set number of days) by running a scheduled task. You will need to view your logs to know the number of stale files and the names of said files.
|
||||
|
||||
Planned features:
|
||||
- Better logging to show more than just the count.
|
||||
- Better logging to show more than just the count. ✅
|
||||
- A page that shows what media is currently flagged for removal. And a button to confirm removal.
|
||||
- Integration with sonarr and radarr apis to delete your media.
|
||||
- Whitelist for shows to ignore. (Seasonal shows)
|
||||
|
||||
Reference in New Issue
Block a user