| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Globalization; |
| | | 4 | | using System.Linq; |
| | | 5 | | using System.Threading; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using Jellyfin.Extensions; |
| | | 8 | | using MediaBrowser.Controller.Configuration; |
| | | 9 | | using MediaBrowser.Controller.Dto; |
| | | 10 | | using MediaBrowser.Controller.Entities; |
| | | 11 | | using MediaBrowser.Controller.Entities.TV; |
| | | 12 | | using MediaBrowser.Controller.IO; |
| | | 13 | | using MediaBrowser.Controller.Library; |
| | | 14 | | using MediaBrowser.Controller.Persistence; |
| | | 15 | | using MediaBrowser.Controller.Providers; |
| | | 16 | | using MediaBrowser.Model.Entities; |
| | | 17 | | using MediaBrowser.Model.Globalization; |
| | | 18 | | using MediaBrowser.Model.IO; |
| | | 19 | | using MediaBrowser.Providers.Manager; |
| | | 20 | | using Microsoft.Extensions.Logging; |
| | | 21 | | |
| | | 22 | | namespace MediaBrowser.Providers.TV; |
| | | 23 | | |
| | | 24 | | /// <summary> |
| | | 25 | | /// Service to manage series metadata. |
| | | 26 | | /// </summary> |
| | | 27 | | public class SeriesMetadataService : MetadataService<Series, SeriesInfo> |
| | | 28 | | { |
| | | 29 | | private readonly ILocalizationManager _localizationManager; |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Initializes a new instance of the <see cref="SeriesMetadataService"/> class. |
| | | 33 | | /// </summary> |
| | | 34 | | /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/>.</param> |
| | | 35 | | /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> |
| | | 36 | | /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param> |
| | | 37 | | /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param> |
| | | 38 | | /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param> |
| | | 39 | | /// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param> |
| | | 40 | | /// <param name="externalDataManager">Instance of the <see cref="IExternalDataManager"/> interface.</param> |
| | | 41 | | /// <param name="itemRepository">Instance of the <see cref="IItemRepository"/> interface.</param> |
| | | 42 | | public SeriesMetadataService( |
| | | 43 | | IServerConfigurationManager serverConfigurationManager, |
| | | 44 | | ILogger<SeriesMetadataService> logger, |
| | | 45 | | IProviderManager providerManager, |
| | | 46 | | IFileSystem fileSystem, |
| | | 47 | | ILibraryManager libraryManager, |
| | | 48 | | ILocalizationManager localizationManager, |
| | | 49 | | IExternalDataManager externalDataManager, |
| | | 50 | | IItemRepository itemRepository) |
| | 21 | 51 | | : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager, externalDataManager, ite |
| | | 52 | | { |
| | 21 | 53 | | _localizationManager = localizationManager; |
| | 21 | 54 | | } |
| | | 55 | | |
| | | 56 | | /// <inheritdoc /> |
| | | 57 | | public override async Task<ItemUpdateType> RefreshMetadata(BaseItem item, MetadataRefreshOptions refreshOptions, Can |
| | | 58 | | { |
| | | 59 | | if (item is Series series) |
| | | 60 | | { |
| | | 61 | | var seasons = series.GetRecursiveChildren(i => i is Season).ToList(); |
| | | 62 | | |
| | | 63 | | foreach (var season in seasons) |
| | | 64 | | { |
| | | 65 | | var hasUpdate = refreshOptions is not null && season.BeforeMetadataRefresh(refreshOptions.ReplaceAllMeta |
| | | 66 | | if (hasUpdate) |
| | | 67 | | { |
| | | 68 | | await season.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait( |
| | | 69 | | } |
| | | 70 | | } |
| | | 71 | | } |
| | | 72 | | |
| | | 73 | | return await base.RefreshMetadata(item, refreshOptions, cancellationToken).ConfigureAwait(false); |
| | | 74 | | } |
| | | 75 | | |
| | | 76 | | /// <inheritdoc /> |
| | | 77 | | protected override async Task AfterMetadataRefresh(Series item, MetadataRefreshOptions refreshOptions, CancellationT |
| | | 78 | | { |
| | | 79 | | await base.AfterMetadataRefresh(item, refreshOptions, cancellationToken).ConfigureAwait(false); |
| | | 80 | | |
| | | 81 | | RemoveObsoleteEpisodes(item); |
| | | 82 | | RemoveObsoleteSeasons(item); |
| | | 83 | | await CreateSeasonsAsync(item, cancellationToken).ConfigureAwait(false); |
| | | 84 | | } |
| | | 85 | | |
| | | 86 | | /// <inheritdoc /> |
| | | 87 | | protected override void MergeData(MetadataResult<Series> source, MetadataResult<Series> target, MetadataField[] lock |
| | | 88 | | { |
| | 0 | 89 | | base.MergeData(source, target, lockedFields, replaceData, mergeMetadataSettings); |
| | | 90 | | |
| | 0 | 91 | | var sourceItem = source.Item; |
| | 0 | 92 | | var targetItem = target.Item; |
| | | 93 | | |
| | 0 | 94 | | if (replaceData || string.IsNullOrEmpty(targetItem.AirTime)) |
| | | 95 | | { |
| | 0 | 96 | | targetItem.AirTime = sourceItem.AirTime; |
| | | 97 | | } |
| | | 98 | | |
| | 0 | 99 | | if (replaceData || !targetItem.Status.HasValue) |
| | | 100 | | { |
| | 0 | 101 | | targetItem.Status = sourceItem.Status; |
| | | 102 | | } |
| | | 103 | | |
| | 0 | 104 | | if (replaceData || targetItem.AirDays is null || targetItem.AirDays.Length == 0) |
| | | 105 | | { |
| | 0 | 106 | | targetItem.AirDays = sourceItem.AirDays; |
| | | 107 | | } |
| | 0 | 108 | | } |
| | | 109 | | |
| | | 110 | | private void RemoveObsoleteSeasons(Series series) |
| | | 111 | | { |
| | | 112 | | // TODO Legacy. It's not really "physical" seasons as any virtual seasons are always converted to non-virtual in |
| | 0 | 113 | | var physicalSeasonNumbers = new HashSet<int>(); |
| | 0 | 114 | | var virtualSeasons = new List<Season>(); |
| | 0 | 115 | | foreach (var existingSeason in series.Children.OfType<Season>()) |
| | | 116 | | { |
| | 0 | 117 | | if (existingSeason.LocationType != LocationType.Virtual && existingSeason.IndexNumber.HasValue) |
| | | 118 | | { |
| | 0 | 119 | | physicalSeasonNumbers.Add(existingSeason.IndexNumber.Value); |
| | | 120 | | } |
| | 0 | 121 | | else if (existingSeason.LocationType == LocationType.Virtual) |
| | | 122 | | { |
| | 0 | 123 | | virtualSeasons.Add(existingSeason); |
| | | 124 | | } |
| | | 125 | | } |
| | | 126 | | |
| | 0 | 127 | | foreach (var virtualSeason in virtualSeasons) |
| | | 128 | | { |
| | 0 | 129 | | var seasonNumber = virtualSeason.IndexNumber; |
| | | 130 | | // If there's a physical season with the same number or no episodes in the season, delete it |
| | 0 | 131 | | if ((seasonNumber.HasValue && physicalSeasonNumbers.Contains(seasonNumber.Value)) |
| | 0 | 132 | | || virtualSeason.GetEpisodes().Count == 0) |
| | | 133 | | { |
| | 0 | 134 | | Logger.LogInformation("Removing virtual season {SeasonNumber} in series {SeriesName}", virtualSeason.Ind |
| | | 135 | | |
| | 0 | 136 | | LibraryManager.DeleteItem( |
| | 0 | 137 | | virtualSeason, |
| | 0 | 138 | | new DeleteOptions |
| | 0 | 139 | | { |
| | 0 | 140 | | // Internal metadata paths are removed regardless of this. |
| | 0 | 141 | | DeleteFileLocation = false |
| | 0 | 142 | | }, |
| | 0 | 143 | | false); |
| | | 144 | | } |
| | | 145 | | } |
| | 0 | 146 | | } |
| | | 147 | | |
| | | 148 | | private void RemoveObsoleteEpisodes(Series series) |
| | | 149 | | { |
| | 0 | 150 | | var episodesBySeason = series.GetEpisodes(null, new DtoOptions(), true) |
| | 0 | 151 | | .OfType<Episode>() |
| | 0 | 152 | | .GroupBy(e => e.ParentIndexNumber) |
| | 0 | 153 | | .ToList(); |
| | | 154 | | |
| | 0 | 155 | | foreach (var seasonEpisodes in episodesBySeason) |
| | | 156 | | { |
| | 0 | 157 | | List<Episode> nonPhysicalEpisodes = []; |
| | 0 | 158 | | List<Episode> physicalEpisodes = []; |
| | 0 | 159 | | foreach (var episode in seasonEpisodes) |
| | | 160 | | { |
| | 0 | 161 | | if (episode.IsVirtualItem || episode.IsMissingEpisode) |
| | | 162 | | { |
| | 0 | 163 | | nonPhysicalEpisodes.Add(episode); |
| | 0 | 164 | | continue; |
| | | 165 | | } |
| | | 166 | | |
| | 0 | 167 | | physicalEpisodes.Add(episode); |
| | | 168 | | } |
| | | 169 | | |
| | | 170 | | // Only consider non-physical episodes |
| | 0 | 171 | | foreach (var episode in nonPhysicalEpisodes) |
| | | 172 | | { |
| | | 173 | | // Episodes without an episode number are practically orphaned and should be deleted |
| | | 174 | | // Episodes with a physical equivalent should be deleted (they are no longer missing) |
| | 0 | 175 | | var shouldKeep = episode.IndexNumber.HasValue && !physicalEpisodes.Any(e => e.ContainsEpisodeNumber(epis |
| | | 176 | | |
| | 0 | 177 | | if (shouldKeep) |
| | | 178 | | { |
| | | 179 | | continue; |
| | | 180 | | } |
| | | 181 | | |
| | 0 | 182 | | DeleteEpisode(episode); |
| | | 183 | | } |
| | | 184 | | } |
| | 0 | 185 | | } |
| | | 186 | | |
| | | 187 | | private void DeleteEpisode(Episode episode) |
| | | 188 | | { |
| | 0 | 189 | | Logger.LogInformation( |
| | 0 | 190 | | "Removing virtual episode S{SeasonNumber}E{EpisodeNumber} in series {SeriesName}", |
| | 0 | 191 | | episode.ParentIndexNumber, |
| | 0 | 192 | | episode.IndexNumber, |
| | 0 | 193 | | episode.SeriesName); |
| | | 194 | | |
| | 0 | 195 | | LibraryManager.DeleteItem( |
| | 0 | 196 | | episode, |
| | 0 | 197 | | new DeleteOptions |
| | 0 | 198 | | { |
| | 0 | 199 | | // Internal metadata paths are removed regardless of this. |
| | 0 | 200 | | DeleteFileLocation = false |
| | 0 | 201 | | }, |
| | 0 | 202 | | false); |
| | 0 | 203 | | } |
| | | 204 | | |
| | | 205 | | private static bool NeedsVirtualSeason(Episode episode, HashSet<Guid> physicalSeasonIds, HashSet<string> physicalSea |
| | | 206 | | { |
| | | 207 | | // Episode has a known season number, needs a season |
| | 0 | 208 | | if (episode.ParentIndexNumber.HasValue) |
| | | 209 | | { |
| | 0 | 210 | | return true; |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | // Not yet processed |
| | 0 | 214 | | if (episode.SeasonId.IsEmpty()) |
| | | 215 | | { |
| | 0 | 216 | | return false; |
| | | 217 | | } |
| | | 218 | | |
| | | 219 | | // Episode has been processed, only needs a virtual season if it isn't |
| | | 220 | | // already linked to a known physical season by ID or path |
| | 0 | 221 | | return !physicalSeasonIds.Contains(episode.SeasonId) |
| | 0 | 222 | | && !physicalSeasonPaths.Contains(System.IO.Path.GetDirectoryName(episode.Path) ?? string.Empty); |
| | | 223 | | } |
| | | 224 | | |
| | | 225 | | /// <summary> |
| | | 226 | | /// Creates seasons for all episodes if they don't exist. |
| | | 227 | | /// If no season number can be determined, a dummy season will be created. |
| | | 228 | | /// </summary> |
| | | 229 | | /// <param name="series">The series.</param> |
| | | 230 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 231 | | /// <returns>The async task.</returns> |
| | | 232 | | private async Task CreateSeasonsAsync(Series series, CancellationToken cancellationToken) |
| | | 233 | | { |
| | | 234 | | var seriesChildren = series.GetRecursiveChildren(i => i is Episode || i is Season); |
| | | 235 | | var seasons = seriesChildren.OfType<Season>().ToList(); |
| | | 236 | | |
| | | 237 | | var physicalSeasonIds = seasons |
| | | 238 | | .Where(e => e.LocationType != LocationType.Virtual) |
| | | 239 | | .Select(e => e.Id) |
| | | 240 | | .ToHashSet(); |
| | | 241 | | |
| | | 242 | | var physicalSeasonPathSet = seasons |
| | | 243 | | .Where(e => e.LocationType != LocationType.Virtual && !string.IsNullOrEmpty(e.Path)) |
| | | 244 | | .Select(e => e.Path) |
| | | 245 | | .ToHashSet(StringComparer.OrdinalIgnoreCase); |
| | | 246 | | |
| | | 247 | | var uniqueSeasonNumbers = seriesChildren |
| | | 248 | | .OfType<Episode>() |
| | | 249 | | .Where(e => NeedsVirtualSeason(e, physicalSeasonIds, physicalSeasonPathSet)) |
| | | 250 | | .Select(e => e.ParentIndexNumber >= 0 ? e.ParentIndexNumber : null) |
| | | 251 | | .Distinct(); |
| | | 252 | | |
| | | 253 | | // Loop through the unique season numbers |
| | | 254 | | foreach (var seasonNumber in uniqueSeasonNumbers) |
| | | 255 | | { |
| | | 256 | | // Null season numbers will have a 'dummy' season created because seasons are always required. |
| | | 257 | | var existingSeason = seasons.FirstOrDefault(i => i.IndexNumber == seasonNumber); |
| | | 258 | | if (existingSeason is null) |
| | | 259 | | { |
| | | 260 | | var seasonName = GetValidSeasonNameForSeries(series, null, seasonNumber); |
| | | 261 | | await CreateSeasonAsync(series, seasonName, seasonNumber, cancellationToken).ConfigureAwait(false); |
| | | 262 | | } |
| | | 263 | | else if (existingSeason.IsVirtualItem) |
| | | 264 | | { |
| | | 265 | | var episodeCount = seriesChildren.OfType<Episode>().Count(e => e.ParentIndexNumber == seasonNumber && !e |
| | | 266 | | if (episodeCount > 0) |
| | | 267 | | { |
| | | 268 | | existingSeason.IsVirtualItem = false; |
| | | 269 | | await existingSeason.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).Configu |
| | | 270 | | } |
| | | 271 | | } |
| | | 272 | | } |
| | | 273 | | } |
| | | 274 | | |
| | | 275 | | /// <summary> |
| | | 276 | | /// Creates a new season, adds it to the database by linking it to the [series] and refreshes the metadata. |
| | | 277 | | /// </summary> |
| | | 278 | | /// <param name="series">The series.</param> |
| | | 279 | | /// <param name="seasonName">The season name.</param> |
| | | 280 | | /// <param name="seasonNumber">The season number.</param> |
| | | 281 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 282 | | /// <returns>The newly created season.</returns> |
| | | 283 | | private async Task CreateSeasonAsync( |
| | | 284 | | Series series, |
| | | 285 | | string? seasonName, |
| | | 286 | | int? seasonNumber, |
| | | 287 | | CancellationToken cancellationToken) |
| | | 288 | | { |
| | | 289 | | Logger.LogInformation("Creating Season {SeasonName} entry for {SeriesName}", seasonName, series.Name); |
| | | 290 | | |
| | | 291 | | var season = new Season |
| | | 292 | | { |
| | | 293 | | Name = seasonName, |
| | | 294 | | IndexNumber = seasonNumber, |
| | | 295 | | Id = LibraryManager.GetNewItemId( |
| | | 296 | | series.Id + (seasonNumber ?? -1).ToString(CultureInfo.InvariantCulture) + seasonName, |
| | | 297 | | typeof(Season)), |
| | | 298 | | IsVirtualItem = false, |
| | | 299 | | SeriesId = series.Id, |
| | | 300 | | SeriesName = series.Name, |
| | | 301 | | SeriesPresentationUniqueKey = series.GetPresentationUniqueKey() |
| | | 302 | | }; |
| | | 303 | | |
| | | 304 | | series.AddChild(season); |
| | | 305 | | await season.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken).Co |
| | | 306 | | } |
| | | 307 | | |
| | | 308 | | private string GetValidSeasonNameForSeries(Series series, string? seasonName, int? seasonNumber) |
| | | 309 | | { |
| | 0 | 310 | | if (string.IsNullOrEmpty(seasonName)) |
| | | 311 | | { |
| | 0 | 312 | | seasonName = seasonNumber switch |
| | 0 | 313 | | { |
| | 0 | 314 | | null => _localizationManager.GetLocalizedString("NameSeasonUnknown"), |
| | 0 | 315 | | 0 => LibraryManager.GetLibraryOptions(series).SeasonZeroDisplayName, |
| | 0 | 316 | | _ => string.Format(CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("NameSeasonNumb |
| | 0 | 317 | | }; |
| | | 318 | | } |
| | | 319 | | |
| | 0 | 320 | | return seasonName; |
| | | 321 | | } |
| | | 322 | | } |