< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.CleanupOrphanedExtras
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/CleanupOrphanedExtras.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 33
Coverable lines: 33
Total lines: 112
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 24
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/4/2026 - 12:15:16 AM Line coverage: 0% (0/33) Branch coverage: 0% (0/24) Total lines: 112 5/4/2026 - 12:15:16 AM Line coverage: 0% (0/33) Branch coverage: 0% (0/24) Total lines: 112

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)0%342180%
PerformAsync()0%4260%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/CleanupOrphanedExtras.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Threading;
 5using System.Threading.Tasks;
 6using Jellyfin.Database.Implementations;
 7using Jellyfin.Server.Migrations.Stages;
 8using Jellyfin.Server.ServerSetupApp;
 9using MediaBrowser.Controller.Channels;
 10using MediaBrowser.Controller.Configuration;
 11using MediaBrowser.Controller.Entities;
 12using MediaBrowser.Controller.Library;
 13using MediaBrowser.Controller.LiveTv;
 14using MediaBrowser.Controller.MediaSegments;
 15using MediaBrowser.Controller.Persistence;
 16using MediaBrowser.Model.IO;
 17using Microsoft.EntityFrameworkCore;
 18using Microsoft.Extensions.Logging;
 19
 20namespace Jellyfin.Server.Migrations.Routines;
 21
 22/// <summary>
 23/// Removes orphaned extras (items with OwnerId pointing to non-existent items).
 24/// Must run before EF migrations that add FK constraints on OwnerId.
 25/// </summary>
 26[JellyfinMigration("2026-01-13T23:00:00", nameof(CleanupOrphanedExtras), Stage = JellyfinMigrationStageTypes.CoreInitial
 27[JellyfinMigrationBackup(JellyfinDb = true)]
 28public class CleanupOrphanedExtras : IAsyncMigrationRoutine
 29{
 30    private readonly IStartupLogger<CleanupOrphanedExtras> _logger;
 31    private readonly IDbContextFactory<JellyfinDbContext> _dbContextFactory;
 32    private readonly ILibraryManager _libraryManager;
 33
 34    /// <summary>
 35    /// Initializes a new instance of the <see cref="CleanupOrphanedExtras"/> class.
 36    /// </summary>
 37    /// <param name="logger">The startup logger.</param>
 38    /// <param name="dbContextFactory">The database context factory.</param>
 39    /// <param name="libraryManager">The library manager.</param>
 40    /// <param name="itemRepository">The item repository.</param>
 41    /// <param name="itemCountService">The item count service.</param>
 42    /// <param name="channelManager">The channel manager.</param>
 43    /// <param name="recordingsManager">The recordings manager.</param>
 44    /// <param name="mediaSourceManager">The media source manager.</param>
 45    /// <param name="mediaSegmentManager">The media segments manager.</param>
 46    /// <param name="configurationManager">The configuration manager.</param>
 47    /// <param name="fileSystem">The file system.</param>
 48    public CleanupOrphanedExtras(
 49        IStartupLogger<CleanupOrphanedExtras> logger,
 50        IDbContextFactory<JellyfinDbContext> dbContextFactory,
 51        ILibraryManager libraryManager,
 52        IItemRepository itemRepository,
 53        IItemCountService itemCountService,
 54        IChannelManager channelManager,
 55        IRecordingsManager recordingsManager,
 56        IMediaSourceManager mediaSourceManager,
 57        IMediaSegmentManager mediaSegmentManager,
 58        IServerConfigurationManager configurationManager,
 59        IFileSystem fileSystem)
 60    {
 061        _logger = logger;
 062        _dbContextFactory = dbContextFactory;
 063        _libraryManager = libraryManager;
 064        BaseItem.LibraryManager ??= libraryManager;
 065        BaseItem.ItemRepository ??= itemRepository;
 066        BaseItem.ItemCountService ??= itemCountService;
 067        BaseItem.ChannelManager ??= channelManager;
 068        BaseItem.MediaSourceManager ??= mediaSourceManager;
 069        BaseItem.MediaSegmentManager ??= mediaSegmentManager;
 070        BaseItem.ConfigurationManager ??= configurationManager;
 071        BaseItem.FileSystem ??= fileSystem;
 072        Video.RecordingsManager ??= recordingsManager;
 073    }
 74
 75    /// <inheritdoc/>
 76    public async Task PerformAsync(CancellationToken cancellationToken)
 77    {
 078        var context = await _dbContextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
 079        await using (context.ConfigureAwait(false))
 80        {
 081            var orphanedItemIds = await context.BaseItems
 082                .Where(b => b.OwnerId.HasValue && !b.OwnerId.Value.Equals(Guid.Empty))
 083                .Where(b => !context.BaseItems.Any(parent => parent.Id.Equals(b.OwnerId!.Value)))
 084                .Select(b => b.Id)
 085                .ToListAsync(cancellationToken)
 086                .ConfigureAwait(false);
 87
 088            if (orphanedItemIds.Count == 0)
 89            {
 090                _logger.LogInformation("No orphaned extras found, skipping migration.");
 091                return;
 92            }
 93
 094            _logger.LogInformation("Found {Count} orphaned extras to remove", orphanedItemIds.Count);
 95
 96            // Batch-resolve items for metadata path cleanup, then delete all at once
 097            var itemsToDelete = new List<BaseItem>();
 098            foreach (var itemId in orphanedItemIds)
 99            {
 0100                var item = _libraryManager.GetItemById(itemId);
 0101                if (item is not null)
 102                {
 0103                    itemsToDelete.Add(item);
 104                }
 105            }
 106
 0107            _libraryManager.DeleteItemsUnsafeFast(itemsToDelete);
 108
 0109            _logger.LogInformation("Successfully removed {Count} orphaned extras", itemsToDelete.Count);
 110        }
 0111    }
 112}