MoveExtractedFiles.cs 12 KB

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