aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Server/Migrations/Routines/20260525010000_CleanupOrphanedExternalData.cs
blob: d8dfe181ca05650456ae8ff24a596d7dcfe83bfc (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations;
using Jellyfin.Server.ServerSetupApp;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Jellyfin.Server.Migrations.Routines;

/// <summary>
/// Removes on-disk external item data (attachments, subtitles, trickplay tiles, chapter images) for items that
/// no longer exist in the <c>BaseItems</c> table. The database side is cleaned up synchronously by
/// <c>IItemPersistenceService.DeleteItem</c>, so the leftover orphans live on the filesystem.
/// </summary>
[JellyfinMigration("2026-05-25T01:00:00", nameof(CleanupOrphanedExternalData))]
[JellyfinMigrationBackup(JellyfinDb = true)]
public class CleanupOrphanedExternalData : IAsyncMigrationRoutine
{
    private const int ProgressLogStep = 500;

    private readonly IStartupLogger<CleanupOrphanedExternalData> _logger;
    private readonly IDbContextFactory<JellyfinDbContext> _dbContextFactory;
    private readonly IApplicationPaths _appPaths;
    private readonly IServerApplicationPaths _serverPaths;

    /// <summary>
    /// Initializes a new instance of the <see cref="CleanupOrphanedExternalData"/> class.
    /// </summary>
    /// <param name="logger">The startup logger.</param>
    /// <param name="dbContextFactory">The database context factory.</param>
    /// <param name="appPaths">The application paths.</param>
    /// <param name="serverPaths">The server application paths.</param>
    public CleanupOrphanedExternalData(
        IStartupLogger<CleanupOrphanedExternalData> logger,
        IDbContextFactory<JellyfinDbContext> dbContextFactory,
        IApplicationPaths appPaths,
        IServerApplicationPaths serverPaths)
    {
        _logger = logger;
        _dbContextFactory = dbContextFactory;
        _appPaths = appPaths;
        _serverPaths = serverPaths;
    }

    /// <inheritdoc/>
    public async Task PerformAsync(CancellationToken cancellationToken)
    {
        var knownIds = await LoadKnownItemIdsAsync(cancellationToken).ConfigureAwait(false);

        CleanupGuidIndexedRoot(
            "attachment",
            Path.Combine(_appPaths.DataPath, "attachments"),
            knownIds,
            deleteSubPath: null,
            cancellationToken);

        CleanupGuidIndexedRoot(
            "subtitle",
            Path.Combine(_appPaths.DataPath, "subtitles"),
            knownIds,
            deleteSubPath: null,
            cancellationToken);

        CleanupGuidIndexedRoot(
            "trickplay",
            _appPaths.TrickplayPath,
            knownIds,
            deleteSubPath: null,
            cancellationToken);

        CleanupGuidIndexedRoot(
            "chapter image",
            Path.Combine(_serverPaths.InternalMetadataPath, "library"),
            knownIds,
            deleteSubPath: "chapters",
            cancellationToken);
    }

    private async Task<HashSet<Guid>> LoadKnownItemIdsAsync(CancellationToken cancellationToken)
    {
        var context = await _dbContextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
        await using (context.ConfigureAwait(false))
        {
            var ids = await context.BaseItems
                .AsNoTracking()
                .Select(b => b.Id)
                .ToListAsync(cancellationToken)
                .ConfigureAwait(false);
            return [.. ids];
        }
    }

    private void CleanupGuidIndexedRoot(
        string label,
        string root,
        HashSet<Guid> knownIds,
        string? deleteSubPath,
        CancellationToken cancellationToken)
    {
        if (string.IsNullOrEmpty(root) || !Directory.Exists(root))
        {
            _logger.LogInformation("Skipping {Label} cleanup; root {Root} does not exist", label, root);
            return;
        }

        _logger.LogInformation("Scanning for orphaned {Label} data under {Root}", label, root);

        var scanned = 0;
        var removed = 0;
        foreach (var prefixDir in Directory.EnumerateDirectories(root))
        {
            cancellationToken.ThrowIfCancellationRequested();

            var prefixName = Path.GetFileName(prefixDir);
            if (prefixName.Length != 2)
            {
                continue;
            }

            foreach (var guidDir in Directory.EnumerateDirectories(prefixDir))
            {
                cancellationToken.ThrowIfCancellationRequested();

                scanned++;
                if (scanned % ProgressLogStep == 0)
                {
                    _logger.LogInformation("Scanning {Label}: {Scanned} directories examined, {Removed} orphans removed so far", label, scanned, removed);
                }

                var leafName = Path.GetFileName(guidDir);
                if (!Guid.TryParse(leafName, CultureInfo.InvariantCulture, out var id))
                {
                    continue;
                }

                if (knownIds.Contains(id))
                {
                    continue;
                }

                var target = deleteSubPath is null ? guidDir : Path.Combine(guidDir, deleteSubPath);
                if (deleteSubPath is not null && !Directory.Exists(target))
                {
                    continue;
                }

                if (TryDelete(target))
                {
                    removed++;
                }
            }
        }

        _logger.LogInformation("Finished {Label} cleanup: scanned {Scanned} directories, removed {Removed} orphans", label, scanned, removed);
    }

    private bool TryDelete(string dir)
    {
        try
        {
            Directory.Delete(dir, recursive: true);
            return true;
        }
        catch (IOException ex)
        {
            _logger.LogWarning(ex, "Failed to delete orphaned directory {Dir}", dir);
        }
        catch (UnauthorizedAccessException ex)
        {
            _logger.LogWarning(ex, "Permission denied deleting orphaned directory {Dir}", dir);
        }

        return false;
    }
}