MoveExtractedFiles.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. #pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using Jellyfin.Data.Enums;
  11. using Jellyfin.Database.Implementations;
  12. using Jellyfin.Database.Implementations.Entities;
  13. using MediaBrowser.Common.Configuration;
  14. using MediaBrowser.Common.Extensions;
  15. using MediaBrowser.Controller.IO;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.IO;
  18. using Microsoft.EntityFrameworkCore;
  19. using Microsoft.Extensions.Logging;
  20. namespace Jellyfin.Server.Migrations.Routines;
  21. /// <summary>
  22. /// Migration to move extracted files to the new directories.
  23. /// </summary>
  24. [JellyfinMigration("2025-04-20T21:00:00", nameof(MoveExtractedFiles), "9063b0Ef-CFF1-4EDC-9A13-74093681A89B")]
  25. #pragma warning disable CS0618 // Type or member is obsolete
  26. public class MoveExtractedFiles : IMigrationRoutine
  27. #pragma warning restore CS0618 // Type or member is obsolete
  28. {
  29. private readonly IApplicationPaths _appPaths;
  30. private readonly ILogger<MoveExtractedFiles> _logger;
  31. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  32. private readonly IPathManager _pathManager;
  33. private readonly IFileSystem _fileSystem;
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="MoveExtractedFiles"/> class.
  36. /// </summary>
  37. /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
  38. /// <param name="logger">The logger.</param>
  39. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  40. /// <param name="pathManager">Instance of the <see cref="IPathManager"/> interface.</param>
  41. /// <param name="dbProvider">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
  42. public MoveExtractedFiles(
  43. IApplicationPaths appPaths,
  44. ILogger<MoveExtractedFiles> logger,
  45. IPathManager pathManager,
  46. IFileSystem fileSystem,
  47. IDbContextFactory<JellyfinDbContext> dbProvider)
  48. {
  49. _appPaths = appPaths;
  50. _logger = logger;
  51. _pathManager = pathManager;
  52. _fileSystem = fileSystem;
  53. _dbProvider = dbProvider;
  54. }
  55. private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
  56. private string AttachmentCachePath => Path.Combine(_appPaths.DataPath, "attachments");
  57. /// <inheritdoc />
  58. public void Perform()
  59. {
  60. const int Limit = 5000;
  61. int itemCount = 0, offset = 0;
  62. var sw = Stopwatch.StartNew();
  63. using var context = _dbProvider.CreateDbContext();
  64. var records = context.BaseItems.Count(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder);
  65. _logger.LogInformation("Checking {Count} items for movable extracted files.", records);
  66. // Make sure directories exist
  67. Directory.CreateDirectory(SubtitleCachePath);
  68. Directory.CreateDirectory(AttachmentCachePath);
  69. do
  70. {
  71. var results = context.BaseItems
  72. .Include(e => e.MediaStreams!.Where(s => s.StreamType == MediaStreamTypeEntity.Subtitle && !s.IsExternal))
  73. .Where(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder)
  74. .OrderBy(e => e.Id)
  75. .Skip(offset)
  76. .Take(Limit)
  77. .Select(b => new Tuple<Guid, string?, ICollection<MediaStreamInfo>?>(b.Id, b.Path, b.MediaStreams)).ToList();
  78. foreach (var result in results)
  79. {
  80. if (MoveSubtitleAndAttachmentFiles(result.Item1, result.Item2, result.Item3, context))
  81. {
  82. itemCount++;
  83. }
  84. }
  85. offset += Limit;
  86. _logger.LogInformation("Checked: {Count} - Moved: {Items} - Time: {Time}", offset, itemCount, sw.Elapsed);
  87. } while (offset < records);
  88. _logger.LogInformation("Moved files for {Count} items in {Time}", itemCount, sw.Elapsed);
  89. // Get all subdirectories with 1 character names (those are the legacy directories)
  90. var subdirectories = Directory.GetDirectories(SubtitleCachePath, "*", SearchOption.AllDirectories).Where(s => s.Length == SubtitleCachePath.Length + 2).ToList();
  91. subdirectories.AddRange(Directory.GetDirectories(AttachmentCachePath, "*", SearchOption.AllDirectories).Where(s => s.Length == AttachmentCachePath.Length + 2));
  92. // Remove all legacy subdirectories
  93. foreach (var subdir in subdirectories)
  94. {
  95. Directory.Delete(subdir, true);
  96. }
  97. // Remove old cache path
  98. var attachmentCachePath = Path.Join(_appPaths.CachePath, "attachments");
  99. if (Directory.Exists(attachmentCachePath))
  100. {
  101. Directory.Delete(attachmentCachePath, true);
  102. }
  103. _logger.LogInformation("Cleaned up left over subtitles and attachments.");
  104. }
  105. private bool MoveSubtitleAndAttachmentFiles(Guid id, string? path, ICollection<MediaStreamInfo>? mediaStreams, JellyfinDbContext context)
  106. {
  107. var itemIdString = id.ToString("N", CultureInfo.InvariantCulture);
  108. var modified = false;
  109. if (mediaStreams is not null)
  110. {
  111. foreach (var mediaStream in mediaStreams)
  112. {
  113. if (mediaStream.Codec is null)
  114. {
  115. continue;
  116. }
  117. var mediaStreamIndex = mediaStream.StreamIndex;
  118. var extension = GetSubtitleExtension(mediaStream.Codec);
  119. var oldSubtitleCachePath = GetOldSubtitleCachePath(path, mediaStreamIndex, extension);
  120. if (string.IsNullOrEmpty(oldSubtitleCachePath) || !File.Exists(oldSubtitleCachePath))
  121. {
  122. continue;
  123. }
  124. var newSubtitleCachePath = _pathManager.GetSubtitlePath(itemIdString, mediaStreamIndex, extension);
  125. if (File.Exists(newSubtitleCachePath))
  126. {
  127. File.Delete(oldSubtitleCachePath);
  128. }
  129. else
  130. {
  131. var newDirectory = Path.GetDirectoryName(newSubtitleCachePath);
  132. if (newDirectory is not null)
  133. {
  134. Directory.CreateDirectory(newDirectory);
  135. File.Move(oldSubtitleCachePath, newSubtitleCachePath, false);
  136. _logger.LogDebug("Moved subtitle {Index} for {Item} from {Source} to {Destination}", mediaStreamIndex, id, oldSubtitleCachePath, newSubtitleCachePath);
  137. modified = true;
  138. }
  139. }
  140. }
  141. }
  142. #pragma warning disable CA1309 // Use ordinal string comparison
  143. var attachments = context.AttachmentStreamInfos.Where(a => a.ItemId.Equals(id) && !string.Equals(a.Codec, "mjpeg")).ToList();
  144. #pragma warning restore CA1309 // Use ordinal string comparison
  145. var shouldExtractOneByOne = attachments.Any(a => !string.IsNullOrEmpty(a.Filename)
  146. && (a.Filename.Contains('/', StringComparison.OrdinalIgnoreCase) || a.Filename.Contains('\\', StringComparison.OrdinalIgnoreCase)));
  147. foreach (var attachment in attachments)
  148. {
  149. var attachmentIndex = attachment.Index;
  150. var oldAttachmentPath = GetOldAttachmentDataPath(path, attachmentIndex);
  151. if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
  152. {
  153. oldAttachmentPath = GetOldAttachmentCachePath(itemIdString, attachment, shouldExtractOneByOne);
  154. if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
  155. {
  156. continue;
  157. }
  158. }
  159. var newAttachmentPath = _pathManager.GetAttachmentPath(itemIdString, attachment.Filename ?? attachmentIndex.ToString(CultureInfo.InvariantCulture));
  160. if (File.Exists(newAttachmentPath))
  161. {
  162. File.Delete(oldAttachmentPath);
  163. }
  164. else
  165. {
  166. var newDirectory = Path.GetDirectoryName(newAttachmentPath);
  167. if (newDirectory is not null)
  168. {
  169. Directory.CreateDirectory(newDirectory);
  170. File.Move(oldAttachmentPath, newAttachmentPath, false);
  171. _logger.LogDebug("Moved attachment {Index} for {Item} from {Source} to {Destination}", attachmentIndex, id, oldAttachmentPath, newAttachmentPath);
  172. modified = true;
  173. }
  174. }
  175. }
  176. return modified;
  177. }
  178. private string? GetOldAttachmentDataPath(string? mediaPath, int attachmentStreamIndex)
  179. {
  180. if (mediaPath is null)
  181. {
  182. return null;
  183. }
  184. string filename;
  185. if (_fileSystem.IsPathFile(mediaPath))
  186. {
  187. DateTime? date;
  188. try
  189. {
  190. date = File.GetLastWriteTimeUtc(mediaPath);
  191. }
  192. catch (IOException e)
  193. {
  194. _logger.LogDebug("Skipping attachment at index {Index} for {Path}: {Exception}", attachmentStreamIndex, mediaPath, e.Message);
  195. return null;
  196. }
  197. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Value.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  198. }
  199. else
  200. {
  201. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  202. }
  203. return Path.Join(_appPaths.DataPath, "attachments", filename[..1], filename);
  204. }
  205. private string? GetOldAttachmentCachePath(string mediaSourceId, AttachmentStreamInfo attachment, bool shouldExtractOneByOne)
  206. {
  207. var attachmentFolderPath = Path.Join(_appPaths.CachePath, "attachments", mediaSourceId);
  208. if (shouldExtractOneByOne)
  209. {
  210. return Path.Join(attachmentFolderPath, attachment.Index.ToString(CultureInfo.InvariantCulture));
  211. }
  212. if (string.IsNullOrEmpty(attachment.Filename))
  213. {
  214. return null;
  215. }
  216. return Path.Join(attachmentFolderPath, attachment.Filename);
  217. }
  218. private string? GetOldSubtitleCachePath(string? path, int streamIndex, string outputSubtitleExtension)
  219. {
  220. if (path is null)
  221. {
  222. return null;
  223. }
  224. DateTime? date;
  225. try
  226. {
  227. date = File.GetLastWriteTimeUtc(path);
  228. }
  229. catch (IOException e)
  230. {
  231. _logger.LogDebug("Skipping subtitle at index {Index} for {Path}: {Exception}", streamIndex, path, e.Message);
  232. return null;
  233. }
  234. var ticksParam = string.Empty;
  235. ReadOnlySpan<char> filename = new Guid(MD5.HashData(Encoding.Unicode.GetBytes(path + "_" + streamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Value.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam))) + outputSubtitleExtension;
  236. return Path.Join(SubtitleCachePath, filename[..1], filename);
  237. }
  238. private static string GetSubtitleExtension(string codec)
  239. {
  240. if (codec.ToLower(CultureInfo.InvariantCulture).Equals("ass", StringComparison.OrdinalIgnoreCase)
  241. || codec.ToLower(CultureInfo.InvariantCulture).Equals("ssa", StringComparison.OrdinalIgnoreCase))
  242. {
  243. return "." + codec;
  244. }
  245. else if (codec.Contains("pgs", StringComparison.OrdinalIgnoreCase))
  246. {
  247. return ".sup";
  248. }
  249. else
  250. {
  251. return ".srt";
  252. }
  253. }
  254. }