< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MigrateLinkedChildren
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20260113120000_MigrateLinkedChildren.cs
Line coverage
49%
Covered lines: 200
Uncovered lines: 208
Coverable lines: 408
Total lines: 827
Line coverage: 49%
Branch coverage
33%
Covered branches: 53
Total branches: 160
Branch coverage: 33.1%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/308) Branch coverage: 0% (0/150) Total lines: 6156/9/2026 - 12:16:23 AM Line coverage: 0% (0/325) Branch coverage: 0% (0/154) Total lines: 6448/2/2026 - 12:17:28 AM Line coverage: 0% (0/358) Branch coverage: 0% (0/132) Total lines: 70010/29/2026 - 12:17:11 AM Line coverage: 48.7% (198/406) Branch coverage: 33.1% (53/160) Total lines: 81811/13/2026 - 12:19:51 AM Line coverage: 49% (200/408) Branch coverage: 33.1% (53/160) Total lines: 827 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/308) Branch coverage: 0% (0/150) Total lines: 6156/9/2026 - 12:16:23 AM Line coverage: 0% (0/325) Branch coverage: 0% (0/154) Total lines: 6448/2/2026 - 12:17:28 AM Line coverage: 0% (0/358) Branch coverage: 0% (0/132) Total lines: 70010/29/2026 - 12:17:11 AM Line coverage: 48.7% (198/406) Branch coverage: 33.1% (53/160) Total lines: 81811/13/2026 - 12:19:51 AM Line coverage: 49% (200/408) Branch coverage: 33.1% (53/160) Total lines: 827

Coverage delta

Coverage delta 49 -49

Metrics

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20260113120000_MigrateLinkedChildren.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.Linq;
 5using System.Text.Json;
 6using System.Threading;
 7using System.Threading.Tasks;
 8using Jellyfin.Database.Implementations;
 9using Jellyfin.Database.Implementations.Entities;
 10using Jellyfin.Extensions;
 11using MediaBrowser.Controller;
 12using MediaBrowser.Controller.Entities;
 13using MediaBrowser.Controller.Library;
 14using MediaBrowser.Model.Entities;
 15using Microsoft.EntityFrameworkCore;
 16using Microsoft.Extensions.Logging;
 17using LinkedChildType = Jellyfin.Database.Implementations.Entities.LinkedChildType;
 18
 19namespace Jellyfin.Server.Migrations.Routines;
 20
 21/// <summary>
 22/// Migrates LinkedChildren data from JSON Data column to the LinkedChildren table.
 23/// </summary>
 24[JellyfinMigration("2026-01-13T12:00:00", nameof(MigrateLinkedChildren))]
 25[JellyfinMigrationBackup(JellyfinDb = true)]
 26internal class MigrateLinkedChildren : IDatabaseMigrationRoutine
 27{
 28    private const int ParseProgressLogStep = 25_000;
 29    private const int FileCheckProgressLogStep = 10_000;
 30    private const int ResolveProgressLogStep = 10_000;
 31    private const int DeleteProgressLogStep = 25;
 32    private const string CollectionFolderTypeName = "MediaBrowser.Controller.Entities.CollectionFolder";
 33
 34    private readonly ILogger<MigrateLinkedChildren> _logger;
 35    private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
 36    private readonly ILibraryManager _libraryManager;
 37    private readonly IServerApplicationHost _appHost;
 38    private readonly IServerApplicationPaths _appPaths;
 39
 40    public MigrateLinkedChildren(
 41        ILoggerFactory loggerFactory,
 42        IDbContextFactory<JellyfinDbContext> dbProvider,
 43        ILibraryManager libraryManager,
 44        IServerApplicationHost appHost,
 45        IServerApplicationPaths appPaths)
 46    {
 647        _logger = loggerFactory.CreateLogger<MigrateLinkedChildren>();
 648        _dbProvider = dbProvider;
 649        _libraryManager = libraryManager;
 650        _appHost = appHost;
 651        _appPaths = appPaths;
 652    }
 53
 54    /// <inheritdoc />
 55    public Task PerformAsync(CancellationToken cancellationToken)
 56    {
 57        // This routine predates the async interface and has not been ported to async database access yet.
 658        PerformCore();
 659        return Task.CompletedTask;
 60    }
 61
 62    private void PerformCore()
 63    {
 664        using var context = _dbProvider.CreateDbContext();
 65
 666        var containerTypes = new[]
 667        {
 668            "MediaBrowser.Controller.Entities.Movies.BoxSet",
 669            "MediaBrowser.Controller.Playlists.Playlist",
 670            "MediaBrowser.Controller.Entities.CollectionFolder"
 671        };
 72
 673        var videoTypes = new[]
 674        {
 675            "MediaBrowser.Controller.Entities.Video",
 676            "MediaBrowser.Controller.Entities.Movies.Movie",
 677            "MediaBrowser.Controller.Entities.TV.Episode"
 678        };
 79
 680        var itemsWithData = context.BaseItems
 681            .Where(b => b.Data != null && (containerTypes.Contains(b.Type) || videoTypes.Contains(b.Type)))
 682            .Select(b => new { b.Id, b.Data, b.Type, b.Path, b.IsFolder })
 683            .ToList();
 84
 685        _logger.LogInformation("Found {Count} potential items with LinkedChildren data to process.", itemsWithData.Count
 86
 687        var pathToIdMap = context.BaseItems
 688            .Where(b => b.Path != null)
 689            .Select(b => new { b.Id, b.Path })
 690            .GroupBy(b => b.Path!)
 691            .ToDictionary(g => g.Key, g => g.First().Id);
 92
 93        // Needed to tell a stale cached ItemId apart from one that still points at a real item.
 694        var allItemIds = context.BaseItems.Select(b => b.Id).ToHashSet();
 95
 696        var playlistParentIds = itemsWithData
 697            .Where(b => b.Type == "MediaBrowser.Controller.Playlists.Playlist")
 698            .Select(b => b.Id)
 699            .ToHashSet();
 100
 6101        var droppedChildren = 0;
 6102        var linkedChildrenToAdd = new List<LinkedChildEntity>();
 6103        var processedCount = 0;
 6104        var totalItems = itemsWithData.Count;
 105
 12106        foreach (var item in itemsWithData)
 107        {
 0108            if (string.IsNullOrEmpty(item.Data))
 109            {
 110                continue;
 111            }
 112
 0113            if (processedCount > 0 && processedCount % ParseProgressLogStep == 0)
 114            {
 0115                _logger.LogInformation("Processing LinkedChildren: {Processed}/{Total} items", processedCount, totalItem
 116            }
 117
 118            try
 119            {
 0120                using var doc = JsonDocument.Parse(item.Data);
 121
 0122                var isVideo = videoTypes.Contains(item.Type);
 123
 124                // Handle Video alternate versions
 0125                if (isVideo)
 126                {
 0127                    ProcessVideoAlternateVersions(doc.RootElement, item.Id, pathToIdMap, allItemIds, linkedChildrenToAdd
 128                }
 129
 130                // Handle LinkedChildren (for containers and other items)
 0131                if (!doc.RootElement.TryGetProperty("LinkedChildren", out var linkedChildrenElement) || linkedChildrenEl
 132                {
 0133                    processedCount++;
 0134                    continue;
 135                }
 136
 137                // Legacy entries may hold a path relative to the container that holds them, so the
 138                // container's own location has to be a real path, not a virtual one.
 0139                var itemPath = item.Path is null ? null : _appHost.ExpandVirtualPath(item.Path);
 0140                var containingFolderPath = item.IsFolder ? itemPath : Path.GetDirectoryName(itemPath);
 0141                var sortOrder = 0;
 0142                foreach (var childElement in linkedChildrenElement.EnumerateArray())
 143                {
 0144                    var childId = ResolveChildId(childElement, containingFolderPath, pathToIdMap, allItemIds);
 0145                    if (!childId.HasValue)
 146                    {
 0147                        droppedChildren++;
 0148                        _logger.LogWarning(
 0149                            "Dropping unresolvable LinkedChild of {ParentId}: ItemId {ItemId}, path {ChildPath}",
 0150                            item.Id,
 0151                            GetStringProperty(childElement, "ItemId") ?? "none",
 0152                            GetStringProperty(childElement, "Path") ?? "none");
 0153                        continue;
 154                    }
 155
 0156                    var childType = LinkedChildType.Manual;
 0157                    if (childElement.TryGetProperty("Type", out var typeProp))
 158                    {
 0159                        if (typeProp.ValueKind == JsonValueKind.Number)
 160                        {
 0161                            childType = (LinkedChildType)typeProp.GetInt32();
 162                        }
 0163                        else if (typeProp.ValueKind == JsonValueKind.String)
 164                        {
 0165                            var typeStr = typeProp.GetString();
 0166                            if (Enum.TryParse<LinkedChildType>(typeStr, out var parsedType))
 167                            {
 0168                                childType = parsedType;
 169                            }
 170                        }
 171                    }
 172
 0173                    linkedChildrenToAdd.Add(new LinkedChildEntity
 0174                    {
 0175                        ParentId = item.Id,
 0176                        ChildId = childId.Value,
 0177                        ChildType = childType,
 0178                        SortOrder = sortOrder
 0179                    });
 180
 0181                    sortOrder++;
 182                }
 183
 0184                processedCount++;
 0185            }
 0186            catch (JsonException ex)
 187            {
 0188                _logger.LogWarning(ex, "Failed to parse JSON for item {ItemId}", item.Id);
 0189            }
 190        }
 191
 6192        if (linkedChildrenToAdd.Count > 0)
 193        {
 0194            _logger.LogInformation("Inserting {Count} LinkedChildren records.", linkedChildrenToAdd.Count);
 195
 0196            var existingKeys = context.LinkedChildren
 0197                .Select(lc => new { lc.ParentId, lc.ChildId })
 0198                .ToHashSet();
 199
 200            // A playlist may list the same child more than once, so it cannot be keyed by
 201            // (ParentId, ChildId): skip a playlist wholesale if it already has rows instead, which
 202            // keeps the routine re-runnable without collapsing repeated entries.
 0203            var populatedParentIds = context.LinkedChildren
 0204                .Select(lc => lc.ParentId)
 0205                .Distinct()
 0206                .ToHashSet();
 207
 0208            var toInsert = linkedChildrenToAdd
 0209                .Where(lc => playlistParentIds.Contains(lc.ParentId)
 0210                    ? !populatedParentIds.Contains(lc.ParentId)
 0211                    : !existingKeys.Contains(new { lc.ParentId, lc.ChildId }))
 0212                .ToList();
 213
 0214            if (toInsert.Count > 0)
 215            {
 216                // Every container type other than a playlist keeps a single entry per child.
 217                // Priority: LocalAlternateVersion > LinkedAlternateVersion > Other
 0218                toInsert =
 0219                [
 0220                    .. toInsert.Where(lc => playlistParentIds.Contains(lc.ParentId)),
 0221                    .. toInsert
 0222                        .Where(lc => !playlistParentIds.Contains(lc.ParentId))
 0223                        .OrderBy(lc => lc.ChildType switch
 0224                        {
 0225                            LinkedChildType.LocalAlternateVersion => 0,
 0226                            LinkedChildType.LinkedAlternateVersion => 1,
 0227                            _ => 2
 0228                        })
 0229                        .DistinctBy(lc => new { lc.ParentId, lc.ChildId })
 0230                ];
 231
 0232                var childIds = toInsert.Select(lc => lc.ChildId).Distinct().ToList();
 0233                var existingChildIds = context.BaseItems
 0234                    .WhereOneOrMany(childIds, b => b.Id)
 0235                    .Select(b => b.Id)
 0236                    .ToHashSet();
 237
 0238                toInsert = toInsert.Where(lc => existingChildIds.Contains(lc.ChildId)).ToList();
 239
 240                // Drop linked (user-merged) entries that point at items the parent owns (local
 241                // file-based alternates or extras). These stem from legacy data that merged an
 242                // owned item onto its own primary and would wrongly mark server-merged groups
 243                // as user-merged (splittable).
 0244                var linkedChildIds = toInsert
 0245                    .Where(lc => lc.ChildType == LinkedChildType.LinkedAlternateVersion)
 0246                    .Select(lc => lc.ChildId)
 0247                    .Distinct()
 0248                    .ToList();
 249
 0250                if (linkedChildIds.Count > 0)
 251                {
 0252                    var ownerIdByChildId = context.BaseItems
 0253                        .WhereOneOrMany(linkedChildIds, b => b.Id)
 0254                        .Where(b => b.OwnerId.HasValue)
 0255                        .Select(b => new { b.Id, b.OwnerId })
 0256                        .ToDictionary(b => b.Id, b => b.OwnerId!.Value);
 257
 0258                    var removedCount = toInsert.RemoveAll(lc =>
 0259                        lc.ChildType == LinkedChildType.LinkedAlternateVersion
 0260                        && ownerIdByChildId.TryGetValue(lc.ChildId, out var ownerId)
 0261                        && ownerId.Equals(lc.ParentId));
 262
 0263                    if (removedCount > 0)
 264                    {
 0265                        _logger.LogInformation("Skipped {Count} LinkedAlternateVersion records pointing at items owned b
 266                    }
 267                }
 268
 0269                context.LinkedChildren.AddRange(toInsert);
 0270                context.SaveChanges();
 271
 0272                _logger.LogInformation("Successfully inserted {Count} LinkedChildren records.", toInsert.Count);
 273            }
 274            else
 275            {
 0276                _logger.LogInformation("All LinkedChildren records already exist, nothing to insert.");
 277            }
 278        }
 279        else
 280        {
 6281            _logger.LogInformation("No LinkedChildren data found to migrate.");
 282        }
 283
 6284        _logger.LogInformation(
 6285            "LinkedChildren migration completed. Processed {Count} items, dropped {DroppedCount} unresolvable children."
 6286            processedCount,
 6287            droppedChildren);
 288
 6289        CleanupWrongTypeAlternateVersions(context);
 6290        CleanupOrphanedAlternateVersionBaseItems(context);
 6291        CleanupItemsFromDeletedLibraries(context);
 6292        CleanupStaleFileEntries(context);
 6293        CleanupOrphanedLinkedChildren(context);
 12294    }
 295
 296    private void CleanupWrongTypeAlternateVersions(JellyfinDbContext context)
 297    {
 6298        _logger.LogInformation("Cleaning up alternate version items with wrong type...");
 299
 300        // Find all LocalAlternateVersion relationships where the child is a generic Video
 301        // but the parent is a more specific type (like Movie).
 302        // Since IDs are computed from type + path, just updating the Type column would break ID lookups.
 303        // Instead, delete them and let the runtime recreate them with the correct type during the next library scan.
 6304        var wrongTypeChildIds = context.LinkedChildren
 6305            .Where(lc => lc.ChildType == LinkedChildType.LocalAlternateVersion)
 6306            .Join(
 6307                context.BaseItems,
 6308                lc => lc.ParentId,
 6309                parent => parent.Id,
 6310                (lc, parent) => new { lc.ChildId, ParentType = parent.Type })
 6311            .Join(
 6312                context.BaseItems,
 6313                x => x.ChildId,
 6314                child => child.Id,
 6315                (x, child) => new { x.ChildId, x.ParentType, ChildType = child.Type })
 6316            .Where(x => x.ChildType != x.ParentType)
 6317            .Select(x => x.ChildId)
 6318            .Distinct()
 6319            .ToList();
 320
 6321        if (wrongTypeChildIds.Count == 0)
 322        {
 6323            _logger.LogInformation("No wrong-type alternate version items found.");
 6324            return;
 325        }
 326
 0327        _logger.LogInformation("Found {Count} wrong-type alternate version items to remove.", wrongTypeChildIds.Count);
 328
 0329        var deleted = ResolveAndDeleteItems(wrongTypeChildIds, "wrong-type alternate version items");
 330
 0331        _logger.LogInformation("Removed {Count} wrong-type alternate version items. They will be recreated with the corr
 0332    }
 333
 334    private void CleanupOrphanedAlternateVersionBaseItems(JellyfinDbContext context)
 335    {
 6336        _logger.LogInformation("Starting cleanup of orphaned alternate version BaseItems...");
 337
 338        // Find BaseItems that have OwnerId set (they belonged to another item) and are not extras,
 339        // but no LinkedChild entry references them — meaning they're orphaned alternate versions.
 340        // This happens when a version file is renamed: the old BaseItem remains in the DB
 341        // with a stale OwnerId but nothing links to it anymore.
 6342        var orphanedVersionIds = context.BaseItems
 6343            .Where(b => b.OwnerId.HasValue && b.ExtraType == null)
 6344            .Where(b => !context.LinkedChildren.Any(lc => lc.ChildId.Equals(b.Id)))
 6345            .Select(b => b.Id)
 6346            .ToList();
 347
 6348        if (orphanedVersionIds.Count == 0)
 349        {
 6350            _logger.LogInformation("No orphaned alternate version BaseItems found.");
 6351            return;
 352        }
 353
 0354        _logger.LogInformation("Found {Count} orphaned alternate version BaseItems to remove.", orphanedVersionIds.Count
 355
 0356        var deleted = ResolveAndDeleteItems(orphanedVersionIds, "orphaned alternate version BaseItems");
 357
 0358        _logger.LogInformation("Removed {Count} orphaned alternate version BaseItems.", deleted);
 0359    }
 360
 361    private void CleanupItemsFromDeletedLibraries(JellyfinDbContext context)
 362    {
 6363        _logger.LogInformation("Starting cleanup of items from deleted libraries...");
 364
 365        // Find BaseItems whose TopParentId points to a library (collection folder) that no longer exists.
 366        // This happens when a library is removed but the scan didn't fully clean up all items under it.
 6367        var orphanedIds = context.BaseItems
 6368            .Where(b => b.TopParentId.HasValue)
 6369            .Where(b => !context.BaseItems.Any(lib => lib.Id.Equals(b.TopParentId!.Value)))
 6370            .Select(b => b.Id)
 6371            .ToList();
 372
 6373        if (orphanedIds.Count == 0)
 374        {
 6375            _logger.LogInformation("No items from deleted libraries found.");
 6376            return;
 377        }
 378
 0379        _logger.LogInformation("Found {Count} items from deleted libraries to remove.", orphanedIds.Count);
 380
 0381        var deleted = ResolveAndDeleteItems(orphanedIds, "items from deleted libraries");
 382
 0383        _logger.LogInformation("Removed {Count} items from deleted libraries.", deleted);
 0384    }
 385
 386    private void CleanupStaleFileEntries(JellyfinDbContext context)
 387    {
 6388        _logger.LogInformation("Starting cleanup of items with missing files...");
 389
 390        // Get all library media locations and partition into accessible vs inaccessible.
 391        // This mirrors the scanner's safeguard: if a library root is inaccessible
 392        // (e.g. NAS offline), we skip items under it to avoid false deletions.
 6393        var virtualFolders = _libraryManager.GetVirtualFolders();
 6394        var accessiblePaths = new List<string>();
 6395        var inaccessiblePaths = new List<string>();
 396
 22397        foreach (var folder in virtualFolders)
 398        {
 20399            foreach (var location in folder.Locations)
 400            {
 5401                if (Directory.Exists(location) && Directory.EnumerateFileSystemEntries(location).Any())
 402                {
 5403                    accessiblePaths.Add(location);
 404                }
 405                else
 406                {
 0407                    inaccessiblePaths.Add(location);
 0408                    _logger.LogWarning(
 0409                        "Library location {Path} is inaccessible or empty, skipping file existence checks for items unde
 0410                        location);
 411                }
 412            }
 413        }
 414
 6415        var allLibraryPaths = accessiblePaths.Concat(inaccessiblePaths).ToList();
 416
 417        // Get all non-folder, non-virtual items with paths from the DB
 6418        var itemsWithPaths = context.BaseItems
 6419            .Where(b => b.Path != null && b.Path != string.Empty)
 6420            .Where(b => !b.IsFolder && !b.IsVirtualItem)
 6421            .Select(b => new { b.Id, b.Path })
 6422            .ToList();
 423
 6424        var internalMetadataPath = _appPaths.InternalMetadataPath;
 425
 426        // An item outside every library location is normally left over from a removed media path, but
 427        // it looks exactly the same as one whose storage failed to mount (a wrong bind mount on the
 428        // first container start, for example). Only act on it while every location is readable.
 429        // Resolving no locations at all is the same hazard with none of the evidence: it cannot be
 430        // told apart from an install that has libraries the server has not read yet, and acting on it
 431        // means every file-backed item in the database is outside every location.
 6432        var canRemoveUnrootedItems = inaccessiblePaths.Count == 0 && allLibraryPaths.Count > 0;
 6433        var skippedUnrootedItems = 0;
 6434        var removedUnrootedItems = 0;
 435
 436        // One library losing its definition folder is the same accident confined to that library: it
 437        // contributes no locations, so everything it held reads as unrooted while the other libraries
 438        // still look healthy enough to act on.
 6439        var itemsInMissingLibraries = GetItemsInMissingLibraries(context, virtualFolders);
 6440        var skippedMissingLibraryItems = 0;
 441
 6442        var staleIds = new List<Guid>();
 6443        var checkedCount = 0;
 6444        _logger.LogInformation("Checking {Total} items for missing files.", itemsWithPaths.Count);
 445
 24446        foreach (var item in itemsWithPaths)
 447        {
 448            // A miss on offline storage can block for the mount timeout, so report while scanning.
 6449            if (checkedCount > 0 && checkedCount % FileCheckProgressLogStep == 0)
 450            {
 0451                _logger.LogInformation(
 0452                    "Checking for missing files: {Checked}/{Total} items, {Stale} stale so far.",
 0453                    checkedCount,
 0454                    itemsWithPaths.Count,
 0455                    staleIds.Count);
 456            }
 457
 6458            checkedCount++;
 459
 460            // Expand virtual path placeholders (%AppDataPath%, %MetadataPath%) to real paths
 6461            var path = _appHost.ExpandVirtualPath(item.Path!);
 462
 463            // Skip items stored under internal metadata (images, subtitles, trickplay, etc.)
 6464            if (path.StartsWith(internalMetadataPath, StringComparison.OrdinalIgnoreCase))
 465            {
 466                continue;
 467            }
 468
 6469            if (accessiblePaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
 470            {
 471                // Item is under an accessible library location — check if it still exists
 472                // Directory check covers BDMV/DVD items whose Path points to a folder
 2473                if (!File.Exists(path) && !Directory.Exists(path))
 474                {
 1475                    _logger.LogDebug("Removing item {ItemId}: file {Path} no longer exists.", item.Id, path);
 1476                    staleIds.Add(item.Id);
 477                }
 478            }
 4479            else if (!allLibraryPaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
 480            {
 481                // Item is not under ANY library location (accessible or not) —
 482                // it's orphaned from all libraries (e.g. media path was removed from config)
 4483                if (itemsInMissingLibraries.Contains(item.Id))
 484                {
 485                    // Its library is the thing that went missing, not its media path.
 1486                    skippedMissingLibraryItems++;
 487                }
 3488                else if (canRemoveUnrootedItems)
 489                {
 2490                    _logger.LogDebug("Removing item {ItemId}: path {Path} is outside every library location.", item.Id, 
 2491                    staleIds.Add(item.Id);
 2492                    removedUnrootedItems++;
 493                }
 494                else
 495                {
 1496                    skippedUnrootedItems++;
 497                }
 498            }
 499
 500            // Otherwise: item is under an inaccessible location — skip (storage may be offline)
 501        }
 502
 6503        if (skippedMissingLibraryItems > 0)
 504        {
 1505            _logger.LogWarning(
 1506                "Keeping {Count} items whose library definition is missing from {Path}. Restore the definition or recrea
 1507                skippedMissingLibraryItems,
 1508                _appPaths.DefaultUserViewsPath);
 509        }
 510
 6511        if (skippedUnrootedItems > 0)
 512        {
 1513            if (allLibraryPaths.Count == 0)
 514            {
 1515                _logger.LogWarning(
 1516                    "Keeping {Count} items that are outside every library location because this server resolved no libra
 1517                    skippedUnrootedItems);
 518            }
 519            else
 520            {
 0521                _logger.LogWarning(
 0522                    "Keeping {Count} items that are outside every library location because {LocationCount} library locat
 0523                    skippedUnrootedItems,
 0524                    inaccessiblePaths.Count);
 525            }
 526        }
 527
 6528        if (staleIds.Count == 0)
 529        {
 3530            _logger.LogInformation("No stale items found.");
 3531            return;
 532        }
 533
 534        // Whether an item went because its own file is gone or because nothing claims its path is the
 535        // difference between a handful of deletions and a whole library, so report the split.
 3536        _logger.LogInformation(
 3537            "Found {Count} stale items to remove, {UnrootedCount} of them because their path is outside every library lo
 3538            staleIds.Count,
 3539            removedUnrootedItems);
 540
 3541        var deleted = ResolveAndDeleteItems(staleIds, "items with missing files");
 542
 3543        _logger.LogInformation("Removed {Count} stale items.", deleted);
 3544    }
 545
 546    // Items under a library whose definition folder is gone. Their locations cannot be resolved, so
 547    // they read as unrooted, but the library is what went missing and the media path is still theirs.
 548    private HashSet<Guid> GetItemsInMissingLibraries(JellyfinDbContext context, IReadOnlyList<VirtualFolderInfo> virtual
 549    {
 6550        var liveLibraryPaths = virtualFolders
 6551            .Select(folder => Path.Combine(_appPaths.DefaultUserViewsPath, folder.Name))
 6552            .ToHashSet(StringComparer.OrdinalIgnoreCase);
 553
 6554        var missingLibraryIds = context.BaseItems
 6555            .Where(b => b.Type == CollectionFolderTypeName && b.Path != null)
 6556            .Select(b => new { b.Id, b.Path })
 6557            .ToList()
 6558            .Where(b => !liveLibraryPaths.Contains(_appHost.ExpandVirtualPath(b.Path!)))
 6559            .Select(b => b.Id)
 6560            .ToList();
 561
 6562        if (missingLibraryIds.Count == 0)
 563        {
 5564            return [];
 565        }
 566
 1567        _logger.LogWarning(
 1568            "{Count} library definition(s) known to the database are not in {Path}.",
 1569            missingLibraryIds.Count,
 1570            _appPaths.DefaultUserViewsPath);
 571
 1572        return context.AncestorIds
 1573            .WhereOneOrMany(missingLibraryIds, a => a.ParentItemId)
 1574            .Select(a => a.ItemId)
 1575            .ToHashSet();
 576    }
 577
 578    private int ResolveAndDeleteItems(IReadOnlyCollection<Guid> ids, string description)
 579    {
 3580        if (ids.Count == 0)
 581        {
 0582            return 0;
 583        }
 584
 3585        return DeleteItems(ResolveItems(ids, description), description);
 586    }
 587
 588    private List<BaseItem> ResolveItems(IReadOnlyCollection<Guid> ids, string description)
 589    {
 590        // Each lookup is a separate repository read; cached ones are fast, so this only reports
 591        // once a set is large enough for the reads to add up to a noticeable stretch.
 3592        var items = new List<BaseItem>(ids.Count);
 3593        var processed = 0;
 12594        foreach (var id in ids)
 595        {
 3596            if (processed > 0 && processed % ResolveProgressLogStep == 0)
 597            {
 0598                _logger.LogInformation("Loading {Description}: {Processed}/{Total} items", description, processed, ids.C
 599            }
 600
 3601            processed++;
 602
 3603            var item = _libraryManager.GetItemById(id);
 3604            if (item is not null)
 605            {
 3606                items.Add(item);
 607            }
 608        }
 609
 3610        return items;
 611    }
 612
 613    private int DeleteItems(IReadOnlyCollection<BaseItem> items, string description)
 614    {
 3615        if (items.Count == 0)
 616        {
 0617            return 0;
 618        }
 619
 3620        var options = new DeleteOptions { DeleteFileLocation = false, DeleteFromExternalProvider = false };
 3621        var deleted = 0;
 3622        var processed = 0;
 12623        foreach (var item in items)
 624        {
 3625            if (processed > 0 && processed % DeleteProgressLogStep == 0)
 626            {
 0627                _logger.LogInformation("Removing {Description}: {Processed}/{Total} items", description, processed, item
 628            }
 629
 3630            processed++;
 631
 632            try
 633            {
 3634                _libraryManager.DeleteItem(item, options);
 3635                deleted++;
 3636            }
 0637            catch (Exception ex)
 638            {
 0639                _logger.LogWarning(ex, "Skipping item {ItemId} ({ItemName}): delete failed.", item.Id, item.Name ?? "Unk
 0640            }
 641        }
 642
 3643        return deleted;
 644    }
 645
 646    private void CleanupOrphanedLinkedChildren(JellyfinDbContext context)
 647    {
 6648        _logger.LogInformation("Starting cleanup of orphaned LinkedChildren records...");
 649
 650        // Find all LinkedChildren where the ChildId doesn't exist in BaseItems
 6651        var orphanedLinkedChildren = context.LinkedChildren
 6652            .Where(lc => !context.BaseItems.Any(b => b.Id.Equals(lc.ChildId)))
 6653            .ToList();
 654
 6655        if (orphanedLinkedChildren.Count == 0)
 656        {
 6657            _logger.LogInformation("No orphaned LinkedChildren found.");
 6658            return;
 659        }
 660
 0661        _logger.LogInformation("Found {Count} orphaned LinkedChildren records to remove.", orphanedLinkedChildren.Count)
 662
 0663        var orphanedByParent = context.LinkedChildren
 0664            .Where(lc => !context.BaseItems.Any(b => b.Id.Equals(lc.ParentId)))
 0665            .ToList();
 666
 0667        if (orphanedByParent.Count > 0)
 668        {
 0669            _logger.LogInformation("Found {Count} LinkedChildren with non-existent parent.", orphanedByParent.Count);
 0670            orphanedLinkedChildren.AddRange(orphanedByParent);
 671        }
 672
 673        // Remove all orphaned records. Both queries can return the same row, and a playlist may hold
 674        // several rows for one child, so the position is what identifies an entry here.
 0675        var distinctOrphaned = orphanedLinkedChildren.DistinctBy(lc => new { lc.ParentId, lc.SortOrder }).ToList();
 0676        context.LinkedChildren.RemoveRange(distinctOrphaned);
 0677        context.SaveChanges();
 678
 0679        _logger.LogInformation("Successfully removed {Count} orphaned LinkedChildren records.", distinctOrphaned.Count);
 0680    }
 681
 682    /// <summary>
 683    /// Resolves the item a legacy LinkedChild entry points at.
 684    /// </summary>
 685    private static Guid? ResolveChildId(
 686        JsonElement childElement,
 687        string? containingFolderPath,
 688        Dictionary<string, Guid> pathToIdMap,
 689        HashSet<Guid> allItemIds)
 690    {
 691        // Pre-12 data only cached ItemId and re-resolved it from the path whenever the cached value
 692        // went stale (BaseItem.GetLinkedChild in 10.x). An id that no longer exists must therefore
 693        // fall through to the path, or the entry is lost even though its file is still in the library.
 0694        if (TryGetGuidProperty(childElement, "ItemId", out var itemId) && allItemIds.Contains(itemId))
 695        {
 0696            return itemId;
 697        }
 698
 0699        var path = GetStringProperty(childElement, "Path");
 0700        if (!string.IsNullOrEmpty(path))
 701        {
 0702            if (pathToIdMap.TryGetValue(path, out var idByPath))
 703            {
 0704                return idByPath;
 705            }
 706
 707            // 10.x resolved entries relative to the container that holds them.
 0708            if (!Path.IsPathRooted(path) && !string.IsNullOrEmpty(containingFolderPath))
 709            {
 0710                string? absolutePath = null;
 711                try
 712                {
 0713                    absolutePath = Path.GetFullPath(Path.Combine(containingFolderPath, path));
 0714                }
 0715                catch (ArgumentException)
 716                {
 717                    // Malformed path, nothing to resolve.
 0718                }
 719
 0720                if (absolutePath is not null && pathToIdMap.TryGetValue(absolutePath, out var idByAbsolutePath))
 721                {
 0722                    return idByAbsolutePath;
 723                }
 724            }
 725        }
 726
 0727        if (TryGetGuidProperty(childElement, "LibraryItemId", out var libraryItemId) && allItemIds.Contains(libraryItemI
 728        {
 0729            return libraryItemId;
 730        }
 731
 0732        return null;
 733    }
 734
 735    private static string? GetStringProperty(JsonElement element, string propertyName)
 0736        => element.TryGetProperty(propertyName, out var property) && property.ValueKind == JsonValueKind.String
 0737            ? property.GetString()
 0738            : null;
 739
 740    private static bool TryGetGuidProperty(JsonElement element, string propertyName, out Guid value)
 741    {
 0742        value = Guid.Empty;
 0743        var raw = GetStringProperty(element, propertyName);
 744
 0745        return !string.IsNullOrEmpty(raw) && Guid.TryParse(raw, out value) && !value.IsEmpty();
 746    }
 747
 748    private void ProcessVideoAlternateVersions(
 749        JsonElement root,
 750        Guid parentId,
 751        Dictionary<string, Guid> pathToIdMap,
 752        HashSet<Guid> allItemIds,
 753        List<LinkedChildEntity> linkedChildrenToAdd)
 754    {
 0755        int sortOrder = 0;
 756
 0757        if (root.TryGetProperty("LocalAlternateVersions", out var localAlternateVersionsElement)
 0758            && localAlternateVersionsElement.ValueKind == JsonValueKind.Array)
 759        {
 0760            foreach (var pathElement in localAlternateVersionsElement.EnumerateArray())
 761            {
 0762                if (pathElement.ValueKind != JsonValueKind.String)
 763                {
 764                    continue;
 765                }
 766
 0767                var path = pathElement.GetString();
 0768                if (string.IsNullOrEmpty(path))
 769                {
 770                    continue;
 771                }
 772
 773                // Try to resolve the path to an ItemId
 0774                if (pathToIdMap.TryGetValue(path, out var childId))
 775                {
 0776                    linkedChildrenToAdd.Add(new LinkedChildEntity
 0777                    {
 0778                        ParentId = parentId,
 0779                        ChildId = childId,
 0780                        ChildType = LinkedChildType.LocalAlternateVersion,
 0781                        SortOrder = sortOrder++
 0782                    });
 783
 0784                    _logger.LogDebug(
 0785                        "Migrating LocalAlternateVersion: Parent={ParentId}, Child={ChildId}, Path={Path}",
 0786                        parentId,
 0787                        childId,
 0788                        path);
 789                }
 790                else
 791                {
 0792                    _logger.LogWarning(
 0793                        "Could not resolve LocalAlternateVersion path to ItemId: {Path} for parent {ParentId}",
 0794                        path,
 0795                        parentId);
 796                }
 797            }
 798        }
 799
 0800        if (root.TryGetProperty("LinkedAlternateVersions", out var linkedAlternateVersionsElement)
 0801            && linkedAlternateVersionsElement.ValueKind == JsonValueKind.Array)
 802        {
 0803            foreach (var linkedChildElement in linkedAlternateVersionsElement.EnumerateArray())
 804            {
 0805                var childId = ResolveChildId(linkedChildElement, null, pathToIdMap, allItemIds);
 0806                if (!childId.HasValue)
 807                {
 0808                    _logger.LogWarning("Could not resolve LinkedAlternateVersion child ID for parent {ParentId}", parent
 0809                    continue;
 810                }
 811
 0812                linkedChildrenToAdd.Add(new LinkedChildEntity
 0813                {
 0814                    ParentId = parentId,
 0815                    ChildId = childId.Value,
 0816                    ChildType = LinkedChildType.LinkedAlternateVersion,
 0817                    SortOrder = sortOrder++
 0818                });
 819
 0820                _logger.LogDebug(
 0821                    "Migrating LinkedAlternateVersion: Parent={ParentId}, Child={ChildId}",
 0822                    parentId,
 0823                    childId.Value);
 824            }
 825        }
 0826    }
 827}

Methods/Properties

.ctor(Microsoft.Extensions.Logging.ILoggerFactory,Microsoft.EntityFrameworkCore.IDbContextFactory`1<Jellyfin.Database.Implementations.JellyfinDbContext>,MediaBrowser.Controller.Library.ILibraryManager,MediaBrowser.Controller.IServerApplicationHost,MediaBrowser.Controller.IServerApplicationPaths)
PerformAsync(System.Threading.CancellationToken)
PerformCore()
CleanupWrongTypeAlternateVersions(Jellyfin.Database.Implementations.JellyfinDbContext)
CleanupOrphanedAlternateVersionBaseItems(Jellyfin.Database.Implementations.JellyfinDbContext)
CleanupItemsFromDeletedLibraries(Jellyfin.Database.Implementations.JellyfinDbContext)
CleanupStaleFileEntries(Jellyfin.Database.Implementations.JellyfinDbContext)
GetItemsInMissingLibraries(Jellyfin.Database.Implementations.JellyfinDbContext,System.Collections.Generic.IReadOnlyList`1<MediaBrowser.Model.Entities.VirtualFolderInfo>)
ResolveAndDeleteItems(System.Collections.Generic.IReadOnlyCollection`1<System.Guid>,System.String)
ResolveItems(System.Collections.Generic.IReadOnlyCollection`1<System.Guid>,System.String)
DeleteItems(System.Collections.Generic.IReadOnlyCollection`1<MediaBrowser.Controller.Entities.BaseItem>,System.String)
CleanupOrphanedLinkedChildren(Jellyfin.Database.Implementations.JellyfinDbContext)
ResolveChildId(System.Text.Json.JsonElement,System.String,System.Collections.Generic.Dictionary`2<System.String,System.Guid>,System.Collections.Generic.HashSet`1<System.Guid>)
GetStringProperty(System.Text.Json.JsonElement,System.String)
TryGetGuidProperty(System.Text.Json.JsonElement,System.String,System.Guid&)
ProcessVideoAlternateVersions(System.Text.Json.JsonElement,System.Guid,System.Collections.Generic.Dictionary`2<System.String,System.Guid>,System.Collections.Generic.HashSet`1<System.Guid>,System.Collections.Generic.List`1<Jellyfin.Database.Implementations.Entities.LinkedChildEntity>)