jellyfin/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs

387 lines
15 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
2016-10-24 02:45:23 +00:00
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Plugins.TheTvdb;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.TV
{
2016-10-27 07:58:33 +00:00
public class MissingEpisodeProvider
{
2019-09-10 20:37:53 +00:00
private const double UnairedEpisodeThresholdDays = 2;
private readonly IServerConfigurationManager _config;
private readonly ILogger _logger;
private readonly ILibraryManager _libraryManager;
2014-12-23 03:58:14 +00:00
private readonly ILocalizationManager _localization;
2015-09-13 23:07:54 +00:00
private readonly IFileSystem _fileSystem;
private readonly TvdbClientManager _tvdbClientManager;
2019-02-15 19:11:27 +00:00
public MissingEpisodeProvider(
ILogger logger,
IServerConfigurationManager config,
ILibraryManager libraryManager,
ILocalizationManager localization,
IFileSystem fileSystem,
TvdbClientManager tvdbClientManager)
{
_logger = logger;
_config = config;
_libraryManager = libraryManager;
2014-12-23 03:58:14 +00:00
_localization = localization;
2015-09-13 23:07:54 +00:00
_fileSystem = fileSystem;
_tvdbClientManager = tvdbClientManager;
}
2018-09-12 17:26:21 +00:00
public async Task<bool> Run(Series series, bool addNewItems, CancellationToken cancellationToken)
{
2020-06-06 19:17:49 +00:00
var tvdbId = series.GetProviderId(MetadataProvider.Tvdb);
2019-02-08 13:39:01 +00:00
if (string.IsNullOrEmpty(tvdbId))
2019-02-07 22:56:57 +00:00
{
2019-02-08 13:39:01 +00:00
return false;
}
2015-11-24 18:45:52 +00:00
var episodes = await _tvdbClientManager.GetAllEpisodesAsync(Convert.ToInt32(tvdbId), series.GetPreferredMetadataLanguage(), cancellationToken);
2019-02-07 22:56:57 +00:00
var episodeLookup = episodes
.Select(i =>
{
2019-02-07 22:56:57 +00:00
DateTime.TryParse(i.FirstAired, out var firstAired);
var seasonNumber = i.AiredSeason.GetValueOrDefault(-1);
var episodeNumber = i.AiredEpisodeNumber.GetValueOrDefault(-1);
2019-09-10 20:37:53 +00:00
return (seasonNumber, episodeNumber, firstAired);
})
2019-02-20 10:03:04 +00:00
.Where(i => i.seasonNumber != -1 && i.episodeNumber != -1)
.OrderBy(i => i.seasonNumber)
.ThenBy(i => i.episodeNumber)
.ToList();
2018-09-12 17:26:21 +00:00
var allRecursiveChildren = series.GetRecursiveChildren();
2019-02-07 22:56:57 +00:00
var hasBadData = HasInvalidContent(allRecursiveChildren);
2014-04-09 02:12:17 +00:00
// Be conservative here to avoid creating missing episodes for ones they already have
2018-09-12 17:26:21 +00:00
var addMissingEpisodes = !hasBadData && _libraryManager.GetLibraryOptions(series).ImportMissingEpisodes;
2019-02-07 22:56:57 +00:00
var anySeasonsRemoved = RemoveObsoleteOrMissingSeasons(allRecursiveChildren, episodeLookup);
2018-09-12 17:26:21 +00:00
if (anySeasonsRemoved)
{
// refresh this
allRecursiveChildren = series.GetRecursiveChildren();
}
2019-02-07 22:56:57 +00:00
var anyEpisodesRemoved = RemoveObsoleteOrMissingEpisodes(allRecursiveChildren, episodeLookup, addMissingEpisodes);
2018-09-12 17:26:21 +00:00
if (anyEpisodesRemoved)
{
2018-09-12 17:26:21 +00:00
// refresh this
allRecursiveChildren = series.GetRecursiveChildren();
}
2014-03-02 15:42:21 +00:00
2018-09-12 17:26:21 +00:00
var hasNewEpisodes = false;
if (addNewItems && series.IsMetadataFetcherEnabled(_libraryManager.GetLibraryOptions(series), TvdbSeriesProvider.Current.Name))
2018-09-12 17:26:21 +00:00
{
2019-02-07 22:56:57 +00:00
hasNewEpisodes = await AddMissingEpisodes(series, allRecursiveChildren, addMissingEpisodes, episodeLookup, cancellationToken)
2018-09-12 17:26:21 +00:00
.ConfigureAwait(false);
}
2015-01-14 04:20:30 +00:00
if (hasNewEpisodes || anySeasonsRemoved || anyEpisodesRemoved)
{
2018-09-12 17:26:21 +00:00
return true;
}
2018-09-12 17:26:21 +00:00
return false;
}
2014-04-09 02:12:17 +00:00
/// <summary>
/// Returns true if a series has any seasons or episodes without season or episode numbers
/// If this data is missing no virtual items will be added in order to prevent possible duplicates
/// </summary>
2019-02-07 22:56:57 +00:00
private bool HasInvalidContent(IList<BaseItem> allItems)
2014-04-09 02:12:17 +00:00
{
return allItems.OfType<Season>().Any(i => !i.IndexNumber.HasValue) ||
allItems.OfType<Episode>().Any(i =>
{
if (!i.ParentIndexNumber.HasValue)
{
return true;
}
// You could have episodes under season 0 with no number
return false;
});
2014-04-09 02:12:17 +00:00
}
2019-02-07 22:56:57 +00:00
private async Task<bool> AddMissingEpisodes(
Series series,
IEnumerable<BaseItem> allItems,
bool addMissingEpisodes,
2019-02-20 10:03:04 +00:00
IReadOnlyCollection<(int seasonNumber, int episodenumber, DateTime firstAired)> episodeLookup,
2014-09-13 14:10:30 +00:00
CancellationToken cancellationToken)
{
var existingEpisodes = allItems.OfType<Episode>().ToList();
2019-02-20 10:03:04 +00:00
var seasonCounts = episodeLookup.GroupBy(e => e.seasonNumber).ToDictionary(g => g.Key, g => g.Count());
var hasChanges = false;
2019-02-07 22:56:57 +00:00
foreach (var tuple in episodeLookup)
{
2019-02-20 10:03:04 +00:00
if (tuple.seasonNumber <= 0 || tuple.episodenumber <= 0)
{
// Ignore episode/season zeros
continue;
}
var existingEpisode = GetExistingEpisode(existingEpisodes, seasonCounts, tuple);
if (existingEpisode != null)
{
continue;
}
2019-02-20 10:03:04 +00:00
var airDate = tuple.firstAired;
var now = DateTime.UtcNow.AddDays(-UnairedEpisodeThresholdDays);
2016-12-08 15:40:20 +00:00
2019-02-07 22:56:57 +00:00
if (airDate < now && addMissingEpisodes || airDate > now)
{
// tvdb has a lot of nearly blank episodes
2019-02-20 10:03:04 +00:00
_logger.LogInformation("Creating virtual missing/unaired episode {0} {1}x{2}", series.Name, tuple.seasonNumber, tuple.episodenumber);
await AddEpisode(series, tuple.seasonNumber, tuple.episodenumber, cancellationToken).ConfigureAwait(false);
hasChanges = true;
}
}
return hasChanges;
}
/// <summary>
/// Removes the virtual entry after a corresponding physical version has been added
/// </summary>
2019-02-07 22:56:57 +00:00
private bool RemoveObsoleteOrMissingEpisodes(
IEnumerable<BaseItem> allRecursiveChildren,
2019-02-20 10:03:04 +00:00
IEnumerable<(int seasonNumber, int episodeNumber, DateTime firstAired)> episodeLookup,
bool allowMissingEpisodes)
{
var existingEpisodes = allRecursiveChildren.OfType<Episode>();
var physicalEpisodes = new List<Episode>();
var virtualEpisodes = new List<Episode>();
foreach (var episode in existingEpisodes)
{
if (episode.LocationType == LocationType.Virtual)
{
virtualEpisodes.Add(episode);
}
else
{
physicalEpisodes.Add(episode);
}
}
var episodesToRemove = virtualEpisodes
.Where(i =>
{
if (!i.IndexNumber.HasValue || !i.ParentIndexNumber.HasValue)
{
return true;
}
var seasonNumber = i.ParentIndexNumber.Value;
var episodeNumber = i.IndexNumber.Value;
// If there's a physical episode with the same season and episode number, delete it
if (physicalEpisodes.Any(p =>
p.ParentIndexNumber.HasValue && p.ParentIndexNumber.Value == seasonNumber &&
p.ContainsEpisodeNumber(episodeNumber)))
{
return true;
}
// If the episode no longer exists in the remote lookup, delete it
2019-02-20 10:03:04 +00:00
if (!episodeLookup.Any(e => e.seasonNumber == seasonNumber && e.episodeNumber == episodeNumber))
{
return true;
}
// If it's missing, but not unaired, remove it
return !allowMissingEpisodes && i.IsMissingEpisode &&
(!i.PremiereDate.HasValue ||
i.PremiereDate.Value.ToLocalTime().Date.AddDays(UnairedEpisodeThresholdDays) <
DateTime.Now.Date);
});
var hasChanges = false;
2018-09-12 17:26:21 +00:00
foreach (var episodeToRemove in episodesToRemove)
{
2018-09-12 17:26:21 +00:00
_libraryManager.DeleteItem(episodeToRemove, new DeleteOptions
2016-02-12 04:54:00 +00:00
{
DeleteFileLocation = true
2018-09-12 17:26:21 +00:00
}, false);
hasChanges = true;
}
return hasChanges;
}
/// <summary>
/// Removes the obsolete or missing seasons.
/// </summary>
2019-02-07 22:56:57 +00:00
/// <param name="allRecursiveChildren"></param>
/// <param name="episodeLookup">The episode lookup.</param>
2019-09-10 20:37:53 +00:00
/// <returns><see cref="bool" />.</returns>
private bool RemoveObsoleteOrMissingSeasons(
IList<BaseItem> allRecursiveChildren,
2019-02-20 10:03:04 +00:00
IEnumerable<(int seasonNumber, int episodeNumber, DateTime firstAired)> episodeLookup)
{
2018-09-12 17:26:21 +00:00
var existingSeasons = allRecursiveChildren.OfType<Season>().ToList();
var physicalSeasons = new List<Season>();
var virtualSeasons = new List<Season>();
foreach (var season in existingSeasons)
{
if (season.LocationType == LocationType.Virtual)
{
virtualSeasons.Add(season);
}
else
{
physicalSeasons.Add(season);
}
}
2018-09-12 17:26:21 +00:00
var allEpisodes = allRecursiveChildren.OfType<Episode>().ToList();
var seasonsToRemove = virtualSeasons
.Where(i =>
{
if (i.IndexNumber.HasValue)
{
var seasonNumber = i.IndexNumber.Value;
// If there's a physical season with the same number, delete it
if (physicalSeasons.Any(p => p.IndexNumber.HasValue && p.IndexNumber.Value == seasonNumber && string.Equals(p.Series.PresentationUniqueKey, i.Series.PresentationUniqueKey, StringComparison.Ordinal)))
{
return true;
}
2018-09-12 17:26:21 +00:00
// If the season no longer exists in the remote lookup, delete it, but only if an existing episode doesn't require it
2019-02-20 10:03:04 +00:00
return episodeLookup.All(e => e.seasonNumber != seasonNumber) && allEpisodes.All(s => s.ParentIndexNumber != seasonNumber || s.IsInSeasonFolder);
}
2014-12-23 03:58:14 +00:00
// Season does not have a number
// Remove if there are no episodes directly in series without a season number
2018-09-12 17:26:21 +00:00
return allEpisodes.All(s => s.ParentIndexNumber.HasValue || s.IsInSeasonFolder);
});
var hasChanges = false;
foreach (var seasonToRemove in seasonsToRemove)
{
2018-09-12 17:26:21 +00:00
_libraryManager.DeleteItem(seasonToRemove, new DeleteOptions
2016-02-12 04:54:00 +00:00
{
DeleteFileLocation = true
2018-09-12 17:26:21 +00:00
}, false);
hasChanges = true;
}
return hasChanges;
}
/// <summary>
/// Adds the episode.
/// </summary>
/// <param name="series">The series.</param>
/// <param name="seasonNumber">The season number.</param>
/// <param name="episodeNumber">The episode number.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
private async Task AddEpisode(Series series, int seasonNumber, int episodeNumber, CancellationToken cancellationToken)
{
var season = series.Children.OfType<Season>()
.FirstOrDefault(i => i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber);
if (season == null)
{
2019-09-10 20:37:53 +00:00
var provider = new DummySeasonProvider(_logger, _localization, _libraryManager, _fileSystem);
2016-05-20 19:45:04 +00:00
season = await provider.AddSeason(series, seasonNumber, true, cancellationToken).ConfigureAwait(false);
}
2019-09-10 20:37:53 +00:00
var name = "Episode " + episodeNumber.ToString(CultureInfo.InvariantCulture);
var episode = new Episode
{
Name = name,
IndexNumber = episodeNumber,
ParentIndexNumber = seasonNumber,
2019-09-10 20:37:53 +00:00
Id = _libraryManager.GetNewItemId(
series.Id + seasonNumber.ToString(CultureInfo.InvariantCulture) + name,
typeof(Episode)),
2016-07-05 05:40:18 +00:00
IsVirtualItem = true,
2019-02-07 22:56:57 +00:00
SeasonId = season?.Id ?? Guid.Empty,
2016-07-05 06:01:31 +00:00
SeriesId = series.Id
};
season.AddChild(episode, cancellationToken);
2019-09-10 20:37:53 +00:00
await episode.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the existing episode.
/// </summary>
/// <param name="existingEpisodes">The existing episodes.</param>
/// <param name="seasonCounts"></param>
/// <param name="episodeTuple"></param>
/// <returns>Episode.</returns>
2019-09-10 20:37:53 +00:00
private Episode GetExistingEpisode(IEnumerable<Episode> existingEpisodes, IReadOnlyDictionary<int, int> seasonCounts, (int seasonNumber, int episodeNumber, DateTime firstAired) episodeTuple)
{
2019-02-20 10:03:04 +00:00
var seasonNumber = episodeTuple.seasonNumber;
var episodeNumber = episodeTuple.episodeNumber;
while (true)
{
var episode = GetExistingEpisode(existingEpisodes, seasonNumber, episodeNumber);
if (episode != null)
{
return episode;
}
seasonNumber--;
if (seasonCounts.ContainsKey(seasonNumber))
{
episodeNumber += seasonCounts[seasonNumber];
}
else
{
break;
}
}
return null;
}
2018-09-12 17:26:21 +00:00
private Episode GetExistingEpisode(IEnumerable<Episode> existingEpisodes, int season, int episode)
2019-09-10 20:37:53 +00:00
=> existingEpisodes.FirstOrDefault(i => i.ParentIndexNumber == season && i.ContainsEpisodeNumber(episode));
}
}