aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Server/Migrations/Routines/RemoveDuplicatePlaylistChildren.cs
blob: ce2be2755c258b6e3397cec58eda63b5e83168cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Linq;
using System.Threading;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;

namespace Jellyfin.Server.Migrations.Routines;

/// <summary>
/// Remove duplicate playlist entries.
/// </summary>
[JellyfinMigration("2025-04-20T19:00:00", nameof(RemoveDuplicatePlaylistChildren), "96C156A2-7A13-4B3B-A8B8-FB80C94D20C0")]
#pragma warning disable CS0618 // Type or member is obsolete
internal class RemoveDuplicatePlaylistChildren : IMigrationRoutine
#pragma warning restore CS0618 // Type or member is obsolete
{
    private readonly ILibraryManager _libraryManager;
    private readonly IPlaylistManager _playlistManager;

    public RemoveDuplicatePlaylistChildren(
        ILibraryManager libraryManager,
        IPlaylistManager playlistManager)
    {
        _libraryManager = libraryManager;
        _playlistManager = playlistManager;
    }

    /// <inheritdoc/>
    public void Perform()
    {
        var playlists = _libraryManager.GetItemList(new InternalItemsQuery
        {
            IncludeItemTypes = [BaseItemKind.Playlist]
        })
        .Cast<Playlist>()
        .Where(p => !p.OpenAccess || !p.OwnerUserId.Equals(Guid.Empty))
        .ToArray();

        if (playlists.Length > 0)
        {
            foreach (var playlist in playlists)
            {
                var linkedChildren = playlist.LinkedChildren;
                if (linkedChildren.Length > 0)
                {
                    var nullItemChildren = linkedChildren.Where(c => c.ItemId is null);
                    var deduplicatedChildren = linkedChildren.DistinctBy(c => c.ItemId);
                    var newLinkedChildren = nullItemChildren.Concat(deduplicatedChildren);
                    playlist.LinkedChildren = linkedChildren;
                    playlist.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult();
                    _playlistManager.SavePlaylistFile(playlist);
                }
            }
        }
    }
}