< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.RestorePlaylistChildrenFromMetadata
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20260729120000_RestorePlaylistChildrenFromMetadata.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 95
Coverable lines: 95
Total lines: 200
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 34
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 8/2/2026 - 12:17:28 AM Line coverage: 0% (0/93) Branch coverage: 0% (0/34) Total lines: 19111/13/2026 - 12:19:51 AM Line coverage: 0% (0/95) Branch coverage: 0% (0/34) Total lines: 200 8/2/2026 - 12:17:28 AM Line coverage: 0% (0/93) Branch coverage: 0% (0/34) Total lines: 19111/13/2026 - 12:19:51 AM Line coverage: 0% (0/95) Branch coverage: 0% (0/34) Total lines: 200

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
PerformAsync(...)100%210%
PerformCore()0%506220%
ReadEntryPaths(...)0%156120%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20260729120000_RestorePlaylistChildrenFromMetadata.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.Linq;
 5using System.Threading;
 6using System.Threading.Tasks;
 7using System.Xml;
 8using Jellyfin.Database.Implementations;
 9using Jellyfin.Database.Implementations.Entities;
 10using MediaBrowser.Controller;
 11using Microsoft.EntityFrameworkCore;
 12using Microsoft.Extensions.Logging;
 13
 14namespace Jellyfin.Server.Migrations.Routines;
 15
 16/// <summary>
 17/// Restores playlist entries from playlist.xml for playlists that lost all of their children.
 18/// </summary>
 19[JellyfinMigration("2026-07-29T12:00:00", nameof(RestorePlaylistChildrenFromMetadata))]
 20internal class RestorePlaylistChildrenFromMetadata : IDatabaseMigrationRoutine
 21{
 22    private const string PlaylistTypeName = "MediaBrowser.Controller.Playlists.Playlist";
 23    private const string PlaylistFileName = "playlist.xml";
 24
 25    private readonly ILogger<RestorePlaylistChildrenFromMetadata> _logger;
 26    private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
 27    private readonly IServerApplicationHost _appHost;
 28
 29    public RestorePlaylistChildrenFromMetadata(
 30        ILoggerFactory loggerFactory,
 31        IDbContextFactory<JellyfinDbContext> dbProvider,
 32        IServerApplicationHost appHost)
 33    {
 034        _logger = loggerFactory.CreateLogger<RestorePlaylistChildrenFromMetadata>();
 035        _dbProvider = dbProvider;
 036        _appHost = appHost;
 037    }
 38
 39    /// <inheritdoc />
 40    public Task PerformAsync(CancellationToken cancellationToken)
 41    {
 42        // This routine predates the async interface and has not been ported to async database access yet.
 043        PerformCore();
 044        return Task.CompletedTask;
 45    }
 46
 47    private void PerformCore()
 48    {
 049        using var context = _dbProvider.CreateDbContext();
 50
 051        var playlists = context.BaseItems
 052            .Where(b => b.Type == PlaylistTypeName && b.Path != null)
 053            .Select(b => new { b.Id, b.Name, b.Path })
 054            .ToList();
 55
 056        if (playlists.Count == 0)
 57        {
 058            return;
 59        }
 60
 061        var childCountByPlaylist = context.LinkedChildren
 062            .Where(lc => context.BaseItems.Any(b => b.Id.Equals(lc.ParentId) && b.Type == PlaylistTypeName))
 063            .GroupBy(lc => lc.ParentId)
 064            .Select(g => new { ParentId = g.Key, Count = g.Count() })
 065            .ToDictionary(g => g.ParentId, g => g.Count);
 66
 067        var pathToIdMap = context.BaseItems
 068            .Where(b => b.Path != null)
 069            .Select(b => new { b.Id, b.Path })
 070            .GroupBy(b => b.Path!)
 071            .ToDictionary(g => g.Key, g => g.First().Id);
 72
 073        var restoredPlaylists = 0;
 074        var restoredEntries = 0;
 75
 076        foreach (var playlist in playlists)
 77        {
 78            // Only directory-based (Jellyfin-managed) playlists keep their entries in playlist.xml.
 79            // A playlist that is itself a file (.m3u and friends) is re-read by the library scan.
 080            var playlistPath = _appHost.ExpandVirtualPath(playlist.Path!);
 081            var metadataPath = Path.Combine(playlistPath, PlaylistFileName);
 082            if (!Directory.Exists(playlistPath) || !File.Exists(metadataPath))
 83            {
 84                continue;
 85            }
 86
 087            var storedPaths = ReadEntryPaths(metadataPath, playlist.Id);
 088            if (storedPaths.Count == 0)
 89            {
 90                continue;
 91            }
 92
 093            var childCount = childCountByPlaylist.GetValueOrDefault(playlist.Id);
 094            if (childCount > 0)
 95            {
 96                // Merging into a playlist that still has entries would resurrect anything the user
 97                // removed while the metadata file was not rewritten, and there is no way to tell the
 98                // two apart. Report the mismatch instead so it can be checked by hand.
 099                if (storedPaths.Count > childCount)
 100                {
 0101                    _logger.LogWarning(
 0102                        "Playlist {PlaylistName} ({PlaylistId}) holds {ChildCount} entries but {MetadataPath} lists {Sto
 0103                        playlist.Name,
 0104                        playlist.Id,
 0105                        childCount,
 0106                        metadataPath,
 0107                        storedPaths.Count);
 108                }
 109
 0110                continue;
 111            }
 112
 0113            var sortOrder = 0;
 0114            foreach (var storedPath in storedPaths)
 115            {
 0116                if (!pathToIdMap.TryGetValue(storedPath, out var childId))
 117                {
 0118                    _logger.LogWarning(
 0119                        "Cannot restore entry {EntryPath} of playlist {PlaylistName}: no library item has that path.",
 0120                        storedPath,
 0121                        playlist.Name);
 0122                    continue;
 123                }
 124
 0125                context.LinkedChildren.Add(new LinkedChildEntity
 0126                {
 0127                    ParentId = playlist.Id,
 0128                    ChildId = childId,
 0129                    ChildType = LinkedChildType.Manual,
 0130                    SortOrder = sortOrder
 0131                });
 132
 0133                sortOrder++;
 134            }
 135
 0136            if (sortOrder > 0)
 137            {
 0138                restoredPlaylists++;
 0139                restoredEntries += sortOrder;
 0140                _logger.LogInformation(
 0141                    "Restored {Count} entries of empty playlist {PlaylistName} ({PlaylistId}) from {MetadataPath}.",
 0142                    sortOrder,
 0143                    playlist.Name,
 0144                    playlist.Id,
 0145                    metadataPath);
 146            }
 147        }
 148
 0149        if (restoredEntries > 0)
 150        {
 0151            context.SaveChanges();
 0152            _logger.LogInformation("Restored {EntryCount} entries across {PlaylistCount} playlists.", restoredEntries, r
 153        }
 0154    }
 155
 156    private List<string> ReadEntryPaths(string metadataPath, Guid playlistId)
 157    {
 0158        var paths = new List<string>();
 0159        var settings = new XmlReaderSettings
 0160        {
 0161            IgnoreComments = true,
 0162            IgnoreWhitespace = true,
 0163            IgnoreProcessingInstructions = true,
 0164            DtdProcessing = DtdProcessing.Prohibit
 0165        };
 166
 167        try
 168        {
 0169            using var reader = XmlReader.Create(metadataPath, settings);
 0170            var inEntry = false;
 0171            while (reader.Read())
 172            {
 0173                if (reader.NodeType != XmlNodeType.Element)
 174                {
 175                    continue;
 176                }
 177
 0178                if (string.Equals(reader.Name, "PlaylistItem", StringComparison.Ordinal))
 179                {
 0180                    inEntry = true;
 181                }
 0182                else if (inEntry && string.Equals(reader.Name, "Path", StringComparison.Ordinal))
 183                {
 0184                    inEntry = false;
 0185                    var value = reader.ReadElementContentAsString();
 0186                    if (!string.IsNullOrWhiteSpace(value))
 187                    {
 0188                        paths.Add(value.Trim());
 189                    }
 190                }
 191            }
 0192        }
 0193        catch (Exception ex) when (ex is XmlException or IOException or UnauthorizedAccessException)
 194        {
 0195            _logger.LogWarning(ex, "Could not read playlist metadata {MetadataPath} of playlist {PlaylistId}.", metadata
 0196        }
 197
 0198        return paths;
 199    }
 200}