< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MoveExtractedFiles
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20250420210000_MoveExtractedFiles.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 125
Coverable lines: 125
Total lines: 329
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 60
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 2/13/2026 - 12:11:21 AM Line coverage: 0% (0/92) Branch coverage: 0% (0/46) Total lines: 3194/19/2026 - 12:14:27 AM Line coverage: 0% (0/123) Branch coverage: 0% (0/56) Total lines: 3195/13/2026 - 12:15:27 AM Line coverage: 0% (0/125) Branch coverage: 0% (0/60) Total lines: 329 2/13/2026 - 12:11:21 AM Line coverage: 0% (0/92) Branch coverage: 0% (0/46) Total lines: 3194/19/2026 - 12:14:27 AM Line coverage: 0% (0/123) Branch coverage: 0% (0/56) Total lines: 3195/13/2026 - 12:15:27 AM Line coverage: 0% (0/125) Branch coverage: 0% (0/60) Total lines: 329

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
get_SubtitleCachePath()100%210%
get_AttachmentCachePath()100%210%
PerformAsync()0%110100%
MoveSubtitleAndAttachmentFiles(...)0%1190340%
GetOldAttachmentDataPath(...)0%2040%
GetOldAttachmentCachePath(...)0%2040%
GetOldSubtitleCachePath(...)0%620%
GetSubtitleExtension(...)0%4260%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20250420210000_MoveExtractedFiles.cs

#LineLine coverage
 1#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Diagnostics;
 6using System.Globalization;
 7using System.IO;
 8using System.Linq;
 9using System.Security.Cryptography;
 10using System.Text;
 11using System.Threading;
 12using System.Threading.Tasks;
 13using Jellyfin.Data.Enums;
 14using Jellyfin.Database.Implementations;
 15using Jellyfin.Database.Implementations.Entities;
 16using Jellyfin.Server.ServerSetupApp;
 17using MediaBrowser.Common.Configuration;
 18using MediaBrowser.Common.Extensions;
 19using MediaBrowser.Controller.IO;
 20using MediaBrowser.Model.IO;
 21using Microsoft.EntityFrameworkCore;
 22using Microsoft.Extensions.Logging;
 23
 24namespace Jellyfin.Server.Migrations.Routines;
 25
 26/// <summary>
 27/// Migration to move extracted files to the new directories.
 28/// </summary>
 29[JellyfinMigration("2025-04-20T21:00:00", nameof(MoveExtractedFiles))]
 30public class MoveExtractedFiles : IAsyncMigrationRoutine
 31{
 32    private readonly IApplicationPaths _appPaths;
 33    private readonly ILogger _logger;
 34    private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
 35    private readonly IPathManager _pathManager;
 36    private readonly IFileSystem _fileSystem;
 37
 38    /// <summary>
 39    /// Initializes a new instance of the <see cref="MoveExtractedFiles"/> class.
 40    /// </summary>
 41    /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
 42    /// <param name="logger">The logger.</param>
 43    /// <param name="startupLogger">The startup logger for Startup UI intigration.</param>
 44    /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
 45    /// <param name="pathManager">Instance of the <see cref="IPathManager"/> interface.</param>
 46    /// <param name="dbProvider">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
 47    public MoveExtractedFiles(
 48        IApplicationPaths appPaths,
 49        ILogger<MoveExtractedFiles> logger,
 50        IStartupLogger<MoveExtractedFiles> startupLogger,
 51        IPathManager pathManager,
 52        IFileSystem fileSystem,
 53        IDbContextFactory<JellyfinDbContext> dbProvider)
 54    {
 055        _appPaths = appPaths;
 056        _logger = startupLogger.With(logger);
 057        _pathManager = pathManager;
 058        _fileSystem = fileSystem;
 059        _dbProvider = dbProvider;
 060    }
 61
 062    private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
 63
 064    private string AttachmentCachePath => Path.Combine(_appPaths.DataPath, "attachments");
 65
 66    /// <inheritdoc />
 67    public async Task PerformAsync(CancellationToken cancellationToken)
 68    {
 69        const int Limit = 5000;
 070        int itemCount = 0;
 71
 072        var sw = Stopwatch.StartNew();
 73
 074        using var context = _dbProvider.CreateDbContext();
 075        var records = context.BaseItems.Count(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.I
 076        _logger.LogInformation("Checking {Count} items for movable extracted files.", records);
 77
 78        // Make sure directories exist
 079        Directory.CreateDirectory(SubtitleCachePath);
 080        Directory.CreateDirectory(AttachmentCachePath);
 81
 082        await foreach (var result in context.BaseItems
 083                          .Include(e => e.MediaStreams!.Where(s => s.StreamType == MediaStreamTypeEntity.Subtitle && !s.
 084                          .Where(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder)
 085                          .Select(b => new
 086                          {
 087                              b.Id,
 088                              b.Path,
 089                              b.MediaStreams
 090                          })
 091                          .OrderBy(e => e.Id)
 092                          .WithPartitionProgress((partition) => _logger.LogInformation("Checked: {Count} - Moved: {Items
 093                          .PartitionEagerAsync(Limit, cancellationToken)
 094                          .WithCancellation(cancellationToken)
 095                          .ConfigureAwait(false))
 96        {
 097            if (MoveSubtitleAndAttachmentFiles(result.Id, result.Path, result.MediaStreams, context))
 98            {
 099                itemCount++;
 100            }
 101        }
 102
 0103        _logger.LogInformation("Moved files for {Count} items in {Time}", itemCount, sw.Elapsed);
 104
 105        // Get all subdirectories with 1 character names (those are the legacy directories)
 106        var subdirectories = Directory.GetDirectories(SubtitleCachePath, "*", SearchOption.AllDirectories).Where(s => s.
 107        subdirectories.AddRange(Directory.GetDirectories(AttachmentCachePath, "*", SearchOption.AllDirectories).Where(s 
 108
 109        // Remove all legacy subdirectories
 0110        foreach (var subdir in subdirectories)
 111        {
 0112            Directory.Delete(subdir, true);
 113        }
 114
 115        // Remove old cache path
 0116        var attachmentCachePath = Path.Join(_appPaths.CachePath, "attachments");
 0117        if (Directory.Exists(attachmentCachePath))
 118        {
 0119            Directory.Delete(attachmentCachePath, true);
 120        }
 121
 0122        _logger.LogInformation("Cleaned up left over subtitles and attachments.");
 0123    }
 124
 125    private bool MoveSubtitleAndAttachmentFiles(Guid id, string? path, ICollection<MediaStreamInfo>? mediaStreams, Jelly
 126    {
 0127        var itemIdString = id.ToString("N", CultureInfo.InvariantCulture);
 0128        var modified = false;
 0129        if (mediaStreams is not null)
 130        {
 0131            foreach (var mediaStream in mediaStreams)
 132            {
 0133                if (mediaStream.Codec is null)
 134                {
 135                    continue;
 136                }
 137
 0138                var mediaStreamIndex = mediaStream.StreamIndex;
 0139                var extension = GetSubtitleExtension(mediaStream.Codec);
 0140                var oldSubtitleCachePath = GetOldSubtitleCachePath(path, mediaStreamIndex, extension);
 0141                if (string.IsNullOrEmpty(oldSubtitleCachePath) || !File.Exists(oldSubtitleCachePath))
 142                {
 143                    continue;
 144                }
 145
 0146                var newSubtitleCachePath = _pathManager.GetSubtitlePath(itemIdString, mediaStreamIndex, extension);
 0147                if (newSubtitleCachePath is null)
 148                {
 149                    continue;
 150                }
 151
 0152                if (File.Exists(newSubtitleCachePath))
 153                {
 0154                    File.Delete(oldSubtitleCachePath);
 155                }
 156                else
 157                {
 0158                    var newDirectory = Path.GetDirectoryName(newSubtitleCachePath);
 0159                    if (newDirectory is not null)
 160                    {
 0161                        Directory.CreateDirectory(newDirectory);
 0162                        File.Move(oldSubtitleCachePath, newSubtitleCachePath, false);
 0163                        _logger.LogDebug("Moved subtitle {Index} for {Item} from {Source} to {Destination}", mediaStream
 164
 0165                        modified = true;
 166                    }
 167                }
 168            }
 169        }
 170
 171#pragma warning disable CA1309 // Use ordinal string comparison
 0172        var attachments = context.AttachmentStreamInfos.Where(a => a.ItemId.Equals(id) && !string.Equals(a.Codec, "mjpeg
 173#pragma warning restore CA1309 // Use ordinal string comparison
 0174        var shouldExtractOneByOne = attachments.Any(a => !string.IsNullOrEmpty(a.Filename)
 0175                                                                              && (a.Filename.Contains('/', StringCompari
 0176        foreach (var attachment in attachments)
 177        {
 0178            var attachmentIndex = attachment.Index;
 0179            var oldAttachmentPath = GetOldAttachmentDataPath(path, attachmentIndex);
 0180            if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
 181            {
 0182                oldAttachmentPath = GetOldAttachmentCachePath(itemIdString, attachment, shouldExtractOneByOne);
 0183                if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
 184                {
 185                    continue;
 186                }
 187            }
 188
 0189            var newAttachmentPath = _pathManager.GetAttachmentPath(itemIdString, attachment.Filename ?? attachmentIndex.
 0190            if (newAttachmentPath is null)
 191            {
 192                continue;
 193            }
 194
 0195            if (File.Exists(newAttachmentPath))
 196            {
 0197                File.Delete(oldAttachmentPath);
 198            }
 199            else
 200            {
 0201                var newDirectory = Path.GetDirectoryName(newAttachmentPath);
 0202                if (newDirectory is not null)
 203                {
 0204                    Directory.CreateDirectory(newDirectory);
 0205                    File.Move(oldAttachmentPath, newAttachmentPath, false);
 0206                    _logger.LogDebug("Moved attachment {Index} for {Item} from {Source} to {Destination}", attachmentInd
 207
 0208                    modified = true;
 209                }
 210            }
 211        }
 212
 0213        return modified;
 214    }
 215
 216    private string? GetOldAttachmentDataPath(string? mediaPath, int attachmentStreamIndex)
 217    {
 0218        if (mediaPath is null)
 219        {
 0220            return null;
 221        }
 222
 223        string filename;
 0224        if (_fileSystem.IsPathFile(mediaPath))
 225        {
 226            DateTime? date;
 227            try
 228            {
 0229                date = File.GetLastWriteTimeUtc(mediaPath);
 0230            }
 0231            catch (IOException e)
 232            {
 0233                _logger.LogDebug("Skipping attachment at index {Index} for {Path}: {Exception}", attachmentStreamIndex, 
 234
 0235                return null;
 236            }
 0237            catch (UnauthorizedAccessException e)
 238            {
 0239                _logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", attachmentStreamIndex, me
 240
 0241                return null;
 242            }
 0243            catch (ArgumentOutOfRangeException e)
 244            {
 0245                _logger.LogDebug("Skipping attachment at index {Index} for {Path}: {Exception}", attachmentStreamIndex, 
 246
 0247                return null;
 248            }
 249
 0250            filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Value.Tick
 251        }
 252        else
 253        {
 0254            filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D",
 255        }
 256
 0257        return Path.Join(_appPaths.DataPath, "attachments", filename[..1], filename);
 0258    }
 259
 260    private string? GetOldAttachmentCachePath(string mediaSourceId, AttachmentStreamInfo attachment, bool shouldExtractO
 261    {
 0262        var attachmentFolderPath = Path.Join(_appPaths.CachePath, "attachments", mediaSourceId);
 0263        if (shouldExtractOneByOne)
 264        {
 0265            return Path.Join(attachmentFolderPath, attachment.Index.ToString(CultureInfo.InvariantCulture));
 266        }
 267
 0268        if (string.IsNullOrEmpty(attachment.Filename))
 269        {
 0270            return null;
 271        }
 272
 0273        return Path.Join(attachmentFolderPath, attachment.Filename);
 274    }
 275
 276    private string? GetOldSubtitleCachePath(string? path, int streamIndex, string outputSubtitleExtension)
 277    {
 0278        if (path is null)
 279        {
 0280            return null;
 281        }
 282
 283        DateTime? date;
 284        try
 285        {
 0286            date = File.GetLastWriteTimeUtc(path);
 0287        }
 0288        catch (ArgumentOutOfRangeException e)
 289        {
 0290            _logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", streamIndex, path, e.Message)
 291
 0292            return null;
 293        }
 0294        catch (UnauthorizedAccessException e)
 295        {
 0296            _logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", streamIndex, path, e.Message)
 297
 0298            return null;
 299        }
 0300        catch (IOException e)
 301        {
 0302            _logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", streamIndex, path, e.Message)
 303
 0304            return null;
 305        }
 306
 0307        var ticksParam = string.Empty;
 0308        ReadOnlySpan<char> filename = new Guid(MD5.HashData(Encoding.Unicode.GetBytes(path + "_" + streamIndex.ToString(
 309
 0310        return Path.Join(SubtitleCachePath, filename[..1], filename);
 0311    }
 312
 313    private static string GetSubtitleExtension(string codec)
 314    {
 0315        if (codec.ToLower(CultureInfo.InvariantCulture).Equals("ass", StringComparison.OrdinalIgnoreCase)
 0316            || codec.ToLower(CultureInfo.InvariantCulture).Equals("ssa", StringComparison.OrdinalIgnoreCase))
 317        {
 0318            return "." + codec;
 319        }
 0320        else if (codec.Contains("pgs", StringComparison.OrdinalIgnoreCase))
 321        {
 0322            return ".sup";
 323        }
 324        else
 325        {
 0326            return ".srt";
 327        }
 328    }
 329}