MoveExtractedFiles.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
  2. using System;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. using Jellyfin.Data.Enums;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.IO;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.MediaInfo;
  17. using Microsoft.Extensions.Logging;
  18. namespace Jellyfin.Server.Migrations.Routines;
  19. /// <summary>
  20. /// Migration to move extracted files to the new directories.
  21. /// </summary>
  22. public class MoveExtractedFiles : IDatabaseMigrationRoutine
  23. {
  24. private readonly IApplicationPaths _appPaths;
  25. private readonly ILibraryManager _libraryManager;
  26. private readonly ILogger<MoveExtractedFiles> _logger;
  27. private readonly IMediaSourceManager _mediaSourceManager;
  28. private readonly IPathManager _pathManager;
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="MoveExtractedFiles"/> class.
  31. /// </summary>
  32. /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
  33. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  34. /// <param name="logger">The logger.</param>
  35. /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
  36. /// <param name="pathManager">Instance of the <see cref="IPathManager"/> interface.</param>
  37. public MoveExtractedFiles(
  38. IApplicationPaths appPaths,
  39. ILibraryManager libraryManager,
  40. ILogger<MoveExtractedFiles> logger,
  41. IMediaSourceManager mediaSourceManager,
  42. IPathManager pathManager)
  43. {
  44. _appPaths = appPaths;
  45. _libraryManager = libraryManager;
  46. _logger = logger;
  47. _mediaSourceManager = mediaSourceManager;
  48. _pathManager = pathManager;
  49. }
  50. private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
  51. private string AttachmentCachePath => Path.Combine(_appPaths.DataPath, "attachments");
  52. /// <inheritdoc />
  53. public Guid Id => new("9063b0Ef-CFF1-4EDC-9A13-74093681A89B");
  54. /// <inheritdoc />
  55. public string Name => "MoveExtractedFiles";
  56. /// <inheritdoc />
  57. public bool PerformOnNewInstall => false;
  58. /// <inheritdoc />
  59. public void Perform()
  60. {
  61. const int Limit = 500;
  62. int itemCount = 0, offset = 0;
  63. var sw = Stopwatch.StartNew();
  64. var itemsQuery = new InternalItemsQuery
  65. {
  66. MediaTypes = [MediaType.Video],
  67. SourceTypes = [SourceType.Library],
  68. IsVirtualItem = false,
  69. IsFolder = false,
  70. Limit = Limit,
  71. StartIndex = offset,
  72. EnableTotalRecordCount = true,
  73. };
  74. var records = _libraryManager.GetItemsResult(itemsQuery).TotalRecordCount;
  75. _logger.LogInformation("Checking {Count} items for movable extracted files.", records);
  76. // Make sure directories exist
  77. Directory.CreateDirectory(SubtitleCachePath);
  78. Directory.CreateDirectory(AttachmentCachePath);
  79. itemsQuery.EnableTotalRecordCount = false;
  80. do
  81. {
  82. itemsQuery.StartIndex = offset;
  83. var result = _libraryManager.GetItemsResult(itemsQuery);
  84. var items = result.Items;
  85. foreach (var item in items)
  86. {
  87. if (MoveSubtitleAndAttachmentFiles(item))
  88. {
  89. itemCount++;
  90. }
  91. }
  92. offset += Limit;
  93. if (offset % 5_000 == 0)
  94. {
  95. _logger.LogInformation("Checked extracted files for {Count} items in {Time}.", offset, sw.Elapsed);
  96. }
  97. } while (offset < records);
  98. _logger.LogInformation("Checked {Checked} items - Moved files for {Items} items in {Time}.", records, itemCount, sw.Elapsed);
  99. // Get all subdirectories with 1 character names (those are the legacy directories)
  100. var subdirectories = Directory.GetDirectories(SubtitleCachePath, "*", SearchOption.AllDirectories).Where(s => s.Length == SubtitleCachePath.Length + 2).ToList();
  101. subdirectories.AddRange(Directory.GetDirectories(AttachmentCachePath, "*", SearchOption.AllDirectories).Where(s => s.Length == AttachmentCachePath.Length + 2));
  102. // Remove all legacy subdirectories
  103. foreach (var subdir in subdirectories)
  104. {
  105. Directory.Delete(subdir, true);
  106. }
  107. // Remove old cache path
  108. var attachmentCachePath = Path.Join(_appPaths.CachePath, "attachments");
  109. if (Directory.Exists(attachmentCachePath))
  110. {
  111. Directory.Delete(attachmentCachePath, true);
  112. }
  113. _logger.LogInformation("Cleaned up left over subtitles and attachments.");
  114. }
  115. private bool MoveSubtitleAndAttachmentFiles(BaseItem item)
  116. {
  117. var mediaStreams = item.GetMediaStreams().Where(s => s.Type == MediaStreamType.Subtitle && !s.IsExternal);
  118. var itemIdString = item.Id.ToString("N", CultureInfo.InvariantCulture);
  119. var modified = false;
  120. foreach (var mediaStream in mediaStreams)
  121. {
  122. if (mediaStream.Codec is null)
  123. {
  124. continue;
  125. }
  126. var mediaStreamIndex = mediaStream.Index;
  127. var extension = GetSubtitleExtension(mediaStream.Codec);
  128. var oldSubtitleCachePath = GetOldSubtitleCachePath(item.Path, mediaStream.Index, extension);
  129. if (string.IsNullOrEmpty(oldSubtitleCachePath) || !File.Exists(oldSubtitleCachePath))
  130. {
  131. continue;
  132. }
  133. var newSubtitleCachePath = _pathManager.GetSubtitlePath(itemIdString, mediaStreamIndex, extension);
  134. if (File.Exists(newSubtitleCachePath))
  135. {
  136. File.Delete(oldSubtitleCachePath);
  137. }
  138. else
  139. {
  140. var newDirectory = Path.GetDirectoryName(newSubtitleCachePath);
  141. if (newDirectory is not null)
  142. {
  143. Directory.CreateDirectory(newDirectory);
  144. File.Move(oldSubtitleCachePath, newSubtitleCachePath, false);
  145. _logger.LogDebug("Moved subtitle {Index} for {Item} from {Source} to {Destination}", mediaStreamIndex, item.Id, oldSubtitleCachePath, newSubtitleCachePath);
  146. modified = true;
  147. }
  148. }
  149. }
  150. var attachments = _mediaSourceManager.GetMediaAttachments(item.Id).Where(a => !string.Equals(a.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)).ToList();
  151. var shouldExtractOneByOne = attachments.Any(a => !string.IsNullOrEmpty(a.FileName)
  152. && (a.FileName.Contains('/', StringComparison.OrdinalIgnoreCase) || a.FileName.Contains('\\', StringComparison.OrdinalIgnoreCase)));
  153. foreach (var attachment in attachments)
  154. {
  155. var attachmentIndex = attachment.Index;
  156. var oldAttachmentPath = GetOldAttachmentDataPath(item.Path, attachmentIndex);
  157. if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
  158. {
  159. oldAttachmentPath = GetOldAttachmentCachePath(itemIdString, attachment, shouldExtractOneByOne);
  160. if (string.IsNullOrEmpty(oldAttachmentPath) || !File.Exists(oldAttachmentPath))
  161. {
  162. continue;
  163. }
  164. }
  165. var newAttachmentPath = _pathManager.GetAttachmentPath(itemIdString, attachment.FileName ?? attachmentIndex.ToString(CultureInfo.InvariantCulture));
  166. if (File.Exists(newAttachmentPath))
  167. {
  168. File.Delete(oldAttachmentPath);
  169. }
  170. else
  171. {
  172. var newDirectory = Path.GetDirectoryName(newAttachmentPath);
  173. if (newDirectory is not null)
  174. {
  175. Directory.CreateDirectory(newDirectory);
  176. File.Move(oldAttachmentPath, newAttachmentPath, false);
  177. _logger.LogDebug("Moved attachment {Index} for {Item} from {Source} to {Destination}", attachmentIndex, item.Id, oldAttachmentPath, newAttachmentPath);
  178. modified = true;
  179. }
  180. }
  181. }
  182. return modified;
  183. }
  184. private string? GetOldAttachmentDataPath(string? mediaPath, int attachmentStreamIndex)
  185. {
  186. if (mediaPath is null)
  187. {
  188. return null;
  189. }
  190. string filename;
  191. var protocol = _mediaSourceManager.GetPathProtocol(mediaPath);
  192. if (protocol == MediaProtocol.File)
  193. {
  194. DateTime? date;
  195. try
  196. {
  197. date = File.GetLastWriteTimeUtc(mediaPath);
  198. }
  199. catch (IOException e)
  200. {
  201. _logger.LogDebug("Skipping attachment at index {Index} for {Path}: {Exception}", attachmentStreamIndex, mediaPath, e.Message);
  202. return null;
  203. }
  204. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Value.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  205. }
  206. else
  207. {
  208. filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture);
  209. }
  210. return Path.Join(_appPaths.DataPath, "attachments", filename[..1], filename);
  211. }
  212. private string? GetOldAttachmentCachePath(string mediaSourceId, MediaAttachment attachment, bool shouldExtractOneByOne)
  213. {
  214. var attachmentFolderPath = Path.Join(_appPaths.CachePath, "attachments", mediaSourceId);
  215. if (shouldExtractOneByOne)
  216. {
  217. return Path.Join(attachmentFolderPath, attachment.Index.ToString(CultureInfo.InvariantCulture));
  218. }
  219. if (string.IsNullOrEmpty(attachment.FileName))
  220. {
  221. return null;
  222. }
  223. return Path.Join(attachmentFolderPath, attachment.FileName);
  224. }
  225. private string? GetOldSubtitleCachePath(string path, int streamIndex, string outputSubtitleExtension)
  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. }