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