| | | 1 | | using System; |
| | | 2 | | using System.Buffers; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.Linq; |
| | | 5 | | using System.Threading; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using Jellyfin.Data.Enums; |
| | | 8 | | using Jellyfin.Database.Implementations; |
| | | 9 | | using Jellyfin.Database.Implementations.Entities; |
| | | 10 | | using MediaBrowser.Controller.Entities; |
| | | 11 | | using MediaBrowser.Controller.Library; |
| | | 12 | | using MediaBrowser.Controller.Persistence; |
| | | 13 | | using MediaBrowser.Controller.Providers; |
| | | 14 | | using MediaBrowser.Model.Globalization; |
| | | 15 | | using MediaBrowser.Model.IO; |
| | | 16 | | using MediaBrowser.Model.Tasks; |
| | | 17 | | using Microsoft.EntityFrameworkCore; |
| | | 18 | | using Microsoft.Extensions.Logging; |
| | | 19 | | |
| | | 20 | | namespace Emby.Server.Implementations.ScheduledTasks.Tasks; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Class PeopleValidationTask. |
| | | 24 | | /// </summary> |
| | | 25 | | public class PeopleValidationTask : IScheduledTask, IConfigurableScheduledTask |
| | | 26 | | { |
| | | 27 | | private readonly ILibraryManager _libraryManager; |
| | | 28 | | private readonly ILocalizationManager _localization; |
| | | 29 | | private readonly IDbContextFactory<JellyfinDbContext> _dbContextFactory; |
| | | 30 | | private readonly IFileSystem _fileSystem; |
| | | 31 | | private readonly ILogger<PeopleValidationTask> _logger; |
| | | 32 | | private readonly IItemTypeLookup _itemTypeLookup; |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Initializes a new instance of the <see cref="PeopleValidationTask" /> class. |
| | | 36 | | /// </summary> |
| | | 37 | | /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param> |
| | | 38 | | /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param> |
| | | 39 | | /// <param name="dbContextFactory">Instance of the <see cref="IDbContextFactory{TContext}"/> interface.</param> |
| | | 40 | | /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param> |
| | | 41 | | /// <param name="logger">Instance of the <see cref="ILogger{PeopleValidationTask}"/> interface.</param> |
| | | 42 | | /// <param name="itemTypeLookup">Instance of the <see cref="IItemTypeLookup"/> interface.</param> |
| | | 43 | | public PeopleValidationTask( |
| | | 44 | | ILibraryManager libraryManager, |
| | | 45 | | ILocalizationManager localization, |
| | | 46 | | IDbContextFactory<JellyfinDbContext> dbContextFactory, |
| | | 47 | | IFileSystem fileSystem, |
| | | 48 | | ILogger<PeopleValidationTask> logger, |
| | | 49 | | IItemTypeLookup itemTypeLookup) |
| | | 50 | | { |
| | 22 | 51 | | _libraryManager = libraryManager; |
| | 22 | 52 | | _localization = localization; |
| | 22 | 53 | | _dbContextFactory = dbContextFactory; |
| | 22 | 54 | | _fileSystem = fileSystem; |
| | 22 | 55 | | _logger = logger; |
| | 22 | 56 | | _itemTypeLookup = itemTypeLookup; |
| | 22 | 57 | | } |
| | | 58 | | |
| | | 59 | | /// <inheritdoc /> |
| | 22 | 60 | | public string Name => _localization.GetLocalizedString("TaskRefreshPeople"); |
| | | 61 | | |
| | | 62 | | /// <inheritdoc /> |
| | 0 | 63 | | public string Description => _localization.GetLocalizedString("TaskRefreshPeopleDescription"); |
| | | 64 | | |
| | | 65 | | /// <inheritdoc /> |
| | 0 | 66 | | public string Category => _localization.GetLocalizedString("TasksLibraryCategory"); |
| | | 67 | | |
| | | 68 | | /// <inheritdoc /> |
| | 0 | 69 | | public string Key => "RefreshPeople"; |
| | | 70 | | |
| | | 71 | | /// <inheritdoc /> |
| | 0 | 72 | | public bool IsHidden => false; |
| | | 73 | | |
| | | 74 | | /// <inheritdoc /> |
| | 0 | 75 | | public bool IsEnabled => true; |
| | | 76 | | |
| | | 77 | | /// <inheritdoc /> |
| | 0 | 78 | | public bool IsLogged => true; |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// Creates the triggers that define when the task will run. |
| | | 82 | | /// </summary> |
| | | 83 | | /// <returns>An <see cref="IEnumerable{TaskTriggerInfo}"/> containing the default trigger infos for this task.</retu |
| | | 84 | | public IEnumerable<TaskTriggerInfo> GetDefaultTriggers() |
| | | 85 | | { |
| | 22 | 86 | | yield return new TaskTriggerInfo |
| | 22 | 87 | | { |
| | 22 | 88 | | Type = TaskTriggerInfoType.IntervalTrigger, |
| | 22 | 89 | | IntervalTicks = TimeSpan.FromDays(7).Ticks |
| | 22 | 90 | | }; |
| | 22 | 91 | | } |
| | | 92 | | |
| | | 93 | | /// <inheritdoc /> |
| | | 94 | | public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken) |
| | | 95 | | { |
| | | 96 | | // People validation performs heavy database writes that contend with an active library scan. |
| | | 97 | | // Defer it until the scan has finished; the task will run again on its next trigger. |
| | 0 | 98 | | if (_libraryManager.IsScanRunning) |
| | | 99 | | { |
| | 0 | 100 | | _logger.LogInformation("Skipping people validation because a library scan is currently running."); |
| | 0 | 101 | | return; |
| | | 102 | | } |
| | | 103 | | |
| | | 104 | | // Phase 1: Deduplicate and remove orphaned people (0-33%) |
| | 0 | 105 | | var context = await _dbContextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 106 | | await using (context.ConfigureAwait(false)) |
| | | 107 | | { |
| | 0 | 108 | | IProgress<double> subProgress = new Progress<double>((val) => progress.Report(val / 3)); |
| | 0 | 109 | | var dupQuery = context.Peoples |
| | 0 | 110 | | .GroupBy(e => new { e.Name, e.PersonType }) |
| | 0 | 111 | | .Where(e => e.Count() > 1) |
| | 0 | 112 | | .Select(e => e.Select(f => f.Id).ToArray()); |
| | | 113 | | |
| | 0 | 114 | | var total = dupQuery.Count(); |
| | | 115 | | |
| | | 116 | | const int PartitionSize = 100; |
| | 0 | 117 | | var iterator = 0; |
| | | 118 | | int itemCounter; |
| | 0 | 119 | | var buffer = ArrayPool<Guid[]>.Shared.Rent(PartitionSize)!; |
| | | 120 | | try |
| | | 121 | | { |
| | | 122 | | do |
| | | 123 | | { |
| | 0 | 124 | | itemCounter = 0; |
| | 0 | 125 | | await foreach (var item in dupQuery |
| | 0 | 126 | | .Take(PartitionSize) |
| | 0 | 127 | | .AsAsyncEnumerable() |
| | 0 | 128 | | .WithCancellation(cancellationToken) |
| | 0 | 129 | | .ConfigureAwait(false)) |
| | | 130 | | { |
| | 0 | 131 | | buffer[itemCounter++] = item; |
| | | 132 | | } |
| | | 133 | | |
| | 0 | 134 | | for (int i = 0; i < itemCounter; i++) |
| | | 135 | | { |
| | 0 | 136 | | var item = buffer[i]; |
| | 0 | 137 | | var reference = item[0]; |
| | 0 | 138 | | var dups = item[1..]; |
| | 0 | 139 | | await context.PeopleBaseItemMap.WhereOneOrMany(dups, e => e.PeopleId) |
| | 0 | 140 | | .ExecuteUpdateAsync(e => e.SetProperty(f => f.PeopleId, reference), cancellationToken) |
| | 0 | 141 | | .ConfigureAwait(false); |
| | 0 | 142 | | await context.Peoples.Where(e => dups.Contains(e.Id)).ExecuteDeleteAsync(cancellationToken).Conf |
| | 0 | 143 | | subProgress.Report(100f / total * ((iterator * PartitionSize) + i)); |
| | 0 | 144 | | } |
| | | 145 | | |
| | 0 | 146 | | iterator++; |
| | 0 | 147 | | } while (itemCounter == PartitionSize && !cancellationToken.IsCancellationRequested); |
| | 0 | 148 | | } |
| | | 149 | | finally |
| | | 150 | | { |
| | 0 | 151 | | ArrayPool<Guid[]>.Shared.Return(buffer); |
| | | 152 | | } |
| | | 153 | | |
| | 0 | 154 | | var peopleToDelete = await context.Peoples |
| | 0 | 155 | | .Where(p => !context.PeopleBaseItemMap.Any(m => m.PeopleId.Equals(p.Id))) |
| | 0 | 156 | | .ExecuteDeleteAsync(cancellationToken) |
| | 0 | 157 | | .ConfigureAwait(false); |
| | 0 | 158 | | _logger.LogInformation("Removed {Count} orphaned people.", peopleToDelete); |
| | | 159 | | |
| | 0 | 160 | | subProgress.Report(100); |
| | 0 | 161 | | } |
| | | 162 | | |
| | | 163 | | // Phase 2: Validate people (33-66%). Runs after orphaned PeopleBaseItemMap entries are |
| | | 164 | | // cleaned up above, so dead people are removed in a single pass instead of requiring a second run. |
| | 0 | 165 | | IProgress<double> validateProgress = new Progress<double>((val) => progress.Report((val / 3) + 33)); |
| | 0 | 166 | | await _libraryManager.ValidatePeopleAsync(validateProgress, cancellationToken).ConfigureAwait(false); |
| | | 167 | | |
| | | 168 | | // Phase 3: Refresh images for people missing them (66-100%) |
| | 0 | 169 | | IProgress<double> refreshProgress = new Progress<double>((val) => progress.Report((val / 3) + 66)); |
| | 0 | 170 | | await RefreshPeopleImagesAsync(refreshProgress, cancellationToken).ConfigureAwait(false); |
| | | 171 | | |
| | 0 | 172 | | progress.Report(100); |
| | 0 | 173 | | } |
| | | 174 | | |
| | | 175 | | private async Task RefreshPeopleImagesAsync(IProgress<double> progress, CancellationToken cancellationToken) |
| | | 176 | | { |
| | 0 | 177 | | var thirtyDaysAgo = DateTime.UtcNow.AddDays(-30); |
| | 0 | 178 | | var personTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Person]; |
| | | 179 | | |
| | 0 | 180 | | var context = await _dbContextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 181 | | await using (context.ConfigureAwait(false)) |
| | | 182 | | { |
| | | 183 | | const int PartitionSize = 100; |
| | | 184 | | |
| | 0 | 185 | | var numPeople = await context.BaseItems |
| | 0 | 186 | | .AsNoTracking() |
| | 0 | 187 | | .Where(b => b.Type == personTypeName) |
| | 0 | 188 | | .Where(b => b.DateLastRefreshed == null || b.DateLastRefreshed < thirtyDaysAgo) |
| | 0 | 189 | | .Where(b => |
| | 0 | 190 | | !b.Images!.Any(i => i.ImageType == ImageInfoImageType.Primary) || |
| | 0 | 191 | | string.IsNullOrEmpty(b.Overview)) |
| | 0 | 192 | | .CountAsync(cancellationToken) |
| | 0 | 193 | | .ConfigureAwait(false); |
| | | 194 | | |
| | 0 | 195 | | _logger.LogDebug("Found {Count} people needing image/overview refresh", numPeople); |
| | | 196 | | |
| | 0 | 197 | | if (numPeople == 0) |
| | | 198 | | { |
| | 0 | 199 | | progress.Report(100); |
| | 0 | 200 | | return; |
| | | 201 | | } |
| | | 202 | | |
| | 0 | 203 | | var numComplete = 0; |
| | 0 | 204 | | var numRefreshed = 0; |
| | | 205 | | |
| | 0 | 206 | | await foreach (var entry in context.BaseItems |
| | 0 | 207 | | .AsNoTracking() |
| | 0 | 208 | | .Where(b => b.Type == personTypeName) |
| | 0 | 209 | | .Where(b => b.DateLastRefreshed == null || b.DateLastRefreshed < thirtyDaysAgo) |
| | 0 | 210 | | .Where(b => |
| | 0 | 211 | | !b.Images!.Any(i => i.ImageType == ImageInfoImageType.Primary) || |
| | 0 | 212 | | string.IsNullOrEmpty(b.Overview)) |
| | 0 | 213 | | .OrderBy(b => b.Id) |
| | 0 | 214 | | .WithPartitionProgress(partition => _logger.LogDebug("Processing people partition {Partition}", partitio |
| | 0 | 215 | | .PartitionEagerAsync(PartitionSize, cancellationToken) |
| | 0 | 216 | | .WithCancellation(cancellationToken) |
| | 0 | 217 | | .ConfigureAwait(false)) |
| | | 218 | | { |
| | 0 | 219 | | if (await RefreshPersonAsync(entry.Id, cancellationToken).ConfigureAwait(false)) |
| | | 220 | | { |
| | 0 | 221 | | numRefreshed++; |
| | | 222 | | } |
| | | 223 | | |
| | 0 | 224 | | numComplete++; |
| | 0 | 225 | | progress.Report(100.0 * numComplete / numPeople); |
| | | 226 | | } |
| | | 227 | | |
| | 0 | 228 | | _logger.LogInformation("Refreshed metadata for {Count} people missing images or overview", numRefreshed); |
| | | 229 | | } |
| | 0 | 230 | | } |
| | | 231 | | |
| | | 232 | | private async Task<bool> RefreshPersonAsync(Guid personId, CancellationToken cancellationToken) |
| | | 233 | | { |
| | | 234 | | try |
| | | 235 | | { |
| | 0 | 236 | | if (_libraryManager.GetItemById(personId) is not Person item) |
| | | 237 | | { |
| | 0 | 238 | | return false; |
| | | 239 | | } |
| | | 240 | | |
| | 0 | 241 | | var hasImage = item.HasImage(MediaBrowser.Model.Entities.ImageType.Primary); |
| | 0 | 242 | | var hasOverview = !string.IsNullOrEmpty(item.Overview); |
| | | 243 | | |
| | 0 | 244 | | var options = new MetadataRefreshOptions(new DirectoryService(_fileSystem)) |
| | 0 | 245 | | { |
| | 0 | 246 | | ImageRefreshMode = hasImage ? MetadataRefreshMode.ValidationOnly : MetadataRefreshMode.Default, |
| | 0 | 247 | | MetadataRefreshMode = hasOverview ? MetadataRefreshMode.ValidationOnly : MetadataRefreshMode.Default |
| | 0 | 248 | | }; |
| | | 249 | | |
| | 0 | 250 | | await item.RefreshMetadata(options, cancellationToken).ConfigureAwait(false); |
| | 0 | 251 | | return true; |
| | | 252 | | } |
| | 0 | 253 | | catch (OperationCanceledException) |
| | | 254 | | { |
| | 0 | 255 | | throw; |
| | | 256 | | } |
| | 0 | 257 | | catch (Exception ex) |
| | | 258 | | { |
| | 0 | 259 | | _logger.LogError(ex, "Error refreshing images for person {PersonId}", personId); |
| | 0 | 260 | | return false; |
| | | 261 | | } |
| | 0 | 262 | | } |
| | | 263 | | } |