< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MoveExtractedFiles
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/MoveExtractedFiles.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 112
Coverable lines: 112
Total lines: 298
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 58
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

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

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/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 Jellyfin.Data.Enums;
 12using Jellyfin.Database.Implementations;
 13using Jellyfin.Database.Implementations.Entities;
 14using MediaBrowser.Common.Configuration;
 15using MediaBrowser.Common.Extensions;
 16using MediaBrowser.Controller.IO;
 17using MediaBrowser.Model.Entities;
 18using MediaBrowser.Model.IO;
 19using Microsoft.EntityFrameworkCore;
 20using Microsoft.Extensions.Logging;
 21
 22namespace Jellyfin.Server.Migrations.Routines;
 23
 24/// <summary>
 25/// Migration to move extracted files to the new directories.
 26/// </summary>
 27[JellyfinMigration("2025-04-20T21:00:00", nameof(MoveExtractedFiles))]
 28#pragma warning disable CS0618 // Type or member is obsolete
 29public class MoveExtractedFiles : IMigrationRoutine
 30#pragma warning restore CS0618 // Type or member is obsolete
 31{
 32    private readonly IApplicationPaths _appPaths;
 33    private readonly ILogger<MoveExtractedFiles> _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="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
 44    /// <param name="pathManager">Instance of the <see cref="IPathManager"/> interface.</param>
 45    /// <param name="dbProvider">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
 46    public MoveExtractedFiles(
 47        IApplicationPaths appPaths,
 48        ILogger<MoveExtractedFiles> logger,
 49        IPathManager pathManager,
 50        IFileSystem fileSystem,
 51        IDbContextFactory<JellyfinDbContext> dbProvider)
 52    {
 053        _appPaths = appPaths;
 054        _logger = logger;
 055        _pathManager = pathManager;
 056        _fileSystem = fileSystem;
 057        _dbProvider = dbProvider;
 058    }
 59
 060    private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
 61
 062    private string AttachmentCachePath => Path.Combine(_appPaths.DataPath, "attachments");
 63
 64    /// <inheritdoc />
 65    public void Perform()
 66    {
 67        const int Limit = 5000;
 068        int itemCount = 0, offset = 0;
 69
 070        var sw = Stopwatch.StartNew();
 71
 072        using var context = _dbProvider.CreateDbContext();
 073        var records = context.BaseItems.Count(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.I
 074        _logger.LogInformation("Checking {Count} items for movable extracted files.", records);
 75
 76        // Make sure directories exist
 077        Directory.CreateDirectory(SubtitleCachePath);
 078        Directory.CreateDirectory(AttachmentCachePath);
 79        do
 80        {
 081            var results = context.BaseItems
 082                            .Include(e => e.MediaStreams!.Where(s => s.StreamType == MediaStreamTypeEntity.Subtitle && !
 083                            .Where(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder)
 084                            .OrderBy(e => e.Id)
 085                            .Skip(offset)
 086                            .Take(Limit)
 087                            .Select(b => new Tuple<Guid, string?, ICollection<MediaStreamInfo>?>(b.Id, b.Path, b.MediaSt
 88
 089            foreach (var result in results)
 90            {
 091                if (MoveSubtitleAndAttachmentFiles(result.Item1, result.Item2, result.Item3, context))
 92                {
 093                    itemCount++;
 94                }
 95            }
 96
 097            offset += Limit;
 098            if (offset > records)
 99            {
 0100                offset = records;
 101            }
 102
 0103            _logger.LogInformation("Checked: {Count} - Moved: {Items} - Time: {Time}", offset, itemCount, sw.Elapsed);
 0104        } while (offset < records);
 105
 0106        _logger.LogInformation("Moved files for {Count} items in {Time}", itemCount, sw.Elapsed);
 107
 108        // Get all subdirectories with 1 character names (those are the legacy directories)
 0109        var subdirectories = Directory.GetDirectories(SubtitleCachePath, "*", SearchOption.AllDirectories).Where(s => s.
 0110        subdirectories.AddRange(Directory.GetDirectories(AttachmentCachePath, "*", SearchOption.AllDirectories).Where(s 
 111
 112        // Remove all legacy subdirectories
 0113        foreach (var subdir in subdirectories)
 114        {
 0115            Directory.Delete(subdir, true);
 116        }
 117
 118        // Remove old cache path
 0119        var attachmentCachePath = Path.Join(_appPaths.CachePath, "attachments");
 0120        if (Directory.Exists(attachmentCachePath))
 121        {
 0122            Directory.Delete(attachmentCachePath, true);
 123        }
 124
 0125        _logger.LogInformation("Cleaned up left over subtitles and attachments.");
 0126    }
 127
 128    private bool MoveSubtitleAndAttachmentFiles(Guid id, string? path, ICollection<MediaStreamInfo>? mediaStreams, Jelly
 129    {
 0130        var itemIdString = id.ToString("N", CultureInfo.InvariantCulture);
 0131        var modified = false;
 0132        if (mediaStreams is not null)
 133        {
 0134            foreach (var mediaStream in mediaStreams)
 135            {
 0136                if (mediaStream.Codec is null)
 137                {
 138                    continue;
 139                }
 140
 0141                var mediaStreamIndex = mediaStream.StreamIndex;
 0142                var extension = GetSubtitleExtension(mediaStream.Codec);
 0143                var oldSubtitleCachePath = GetOldSubtitleCachePath(path, mediaStreamIndex, extension);
 0144                if (string.IsNullOrEmpty(oldSubtitleCachePath) || !File.Exists(oldSubtitleCachePath))
 145                {
 146                    continue;
 147                }
 148
 0149                var newSubtitleCachePath = _pathManager.GetSubtitlePath(itemIdString, mediaStreamIndex, extension);
 0150                if (File.Exists(newSubtitleCachePath))
 151                {
 0152                    File.Delete(oldSubtitleCachePath);
 153                }
 154                else
 155                {
 0156                    var newDirectory = Path.GetDirectoryName(newSubtitleCachePath);
 0157                    if (newDirectory is not null)
 158                    {
 0159                        Directory.CreateDirectory(newDirectory);
 0160                        File.Move(oldSubtitleCachePath, newSubtitleCachePath, false);
 0161                        _logger.LogDebug("Moved subtitle {Index} for {Item} from {Source} to {Destination}", mediaStream
 162
 0163                        modified = true;
 164                    }
 165                }
 166            }
 167        }
 168
 169#pragma warning disable CA1309 // Use ordinal string comparison
 0170        var attachments = context.AttachmentStreamInfos.Where(a => a.ItemId.Equals(id) && !string.Equals(a.Codec, "mjpeg
 171#pragma warning restore CA1309 // Use ordinal string comparison
 0172        var shouldExtractOneByOne = attachments.Any(a => !string.IsNullOrEmpty(a.Filename)
 0173                                                                              && (a.Filename.Contains('/', StringCompari
 0174        foreach (var attachment in attachments)
 175        {
 0176            var attachmentIndex = attachment.Index;
 0177            var oldAttachmentPath = GetOldAttachmentDataPath(path, attachmentIndex);
 0178            if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
 179            {
 0180                oldAttachmentPath = GetOldAttachmentCachePath(itemIdString, attachment, shouldExtractOneByOne);
 0181                if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
 182                {
 183                    continue;
 184                }
 185            }
 186
 0187            var newAttachmentPath = _pathManager.GetAttachmentPath(itemIdString, attachment.Filename ?? attachmentIndex.
 0188            if (File.Exists(newAttachmentPath))
 189            {
 0190                File.Delete(oldAttachmentPath);
 191            }
 192            else
 193            {
 0194                var newDirectory = Path.GetDirectoryName(newAttachmentPath);
 0195                if (newDirectory is not null)
 196                {
 0197                    Directory.CreateDirectory(newDirectory);
 0198                    File.Move(oldAttachmentPath, newAttachmentPath, false);
 0199                    _logger.LogDebug("Moved attachment {Index} for {Item} from {Source} to {Destination}", attachmentInd
 200
 0201                    modified = true;
 202                }
 203            }
 204        }
 205
 0206        return modified;
 207    }
 208
 209    private string? GetOldAttachmentDataPath(string? mediaPath, int attachmentStreamIndex)
 210    {
 0211        if (mediaPath is null)
 212        {
 0213            return null;
 214        }
 215
 216        string filename;
 0217        if (_fileSystem.IsPathFile(mediaPath))
 218        {
 219            DateTime? date;
 220            try
 221            {
 0222                date = File.GetLastWriteTimeUtc(mediaPath);
 0223            }
 0224            catch (IOException e)
 225            {
 0226                _logger.LogDebug("Skipping attachment at index {Index} for {Path}: {Exception}", attachmentStreamIndex, 
 227
 0228                return null;
 229            }
 230
 0231            filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Value.Tick
 232        }
 233        else
 234        {
 0235            filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D",
 236        }
 237
 0238        return Path.Join(_appPaths.DataPath, "attachments", filename[..1], filename);
 0239    }
 240
 241    private string? GetOldAttachmentCachePath(string mediaSourceId, AttachmentStreamInfo attachment, bool shouldExtractO
 242    {
 0243        var attachmentFolderPath = Path.Join(_appPaths.CachePath, "attachments", mediaSourceId);
 0244        if (shouldExtractOneByOne)
 245        {
 0246            return Path.Join(attachmentFolderPath, attachment.Index.ToString(CultureInfo.InvariantCulture));
 247        }
 248
 0249        if (string.IsNullOrEmpty(attachment.Filename))
 250        {
 0251            return null;
 252        }
 253
 0254        return Path.Join(attachmentFolderPath, attachment.Filename);
 255    }
 256
 257    private string? GetOldSubtitleCachePath(string? path, int streamIndex, string outputSubtitleExtension)
 258    {
 0259        if (path is null)
 260        {
 0261            return null;
 262        }
 263
 264        DateTime? date;
 265        try
 266        {
 0267            date = File.GetLastWriteTimeUtc(path);
 0268        }
 0269        catch (IOException e)
 270        {
 0271            _logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", streamIndex, path, e.Message)
 272
 0273            return null;
 274        }
 275
 0276        var ticksParam = string.Empty;
 0277        ReadOnlySpan<char> filename = new Guid(MD5.HashData(Encoding.Unicode.GetBytes(path + "_" + streamIndex.ToString(
 278
 0279        return Path.Join(SubtitleCachePath, filename[..1], filename);
 0280    }
 281
 282    private static string GetSubtitleExtension(string codec)
 283    {
 0284        if (codec.ToLower(CultureInfo.InvariantCulture).Equals("ass", StringComparison.OrdinalIgnoreCase)
 0285            || codec.ToLower(CultureInfo.InvariantCulture).Equals("ssa", StringComparison.OrdinalIgnoreCase))
 286        {
 0287            return "." + codec;
 288        }
 0289        else if (codec.Contains("pgs", StringComparison.OrdinalIgnoreCase))
 290        {
 0291            return ".sup";
 292        }
 293        else
 294        {
 0295            return ".srt";
 296        }
 297    }
 298}