MigrateKeyframeData.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. using System;
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text.Json;
  8. using Jellyfin.Data.Enums;
  9. using Jellyfin.Database.Implementations;
  10. using Jellyfin.Database.Implementations.Entities;
  11. using Jellyfin.Extensions.Json;
  12. using Jellyfin.Server.ServerSetupApp;
  13. using MediaBrowser.Common.Configuration;
  14. using MediaBrowser.Common.Extensions;
  15. using Microsoft.EntityFrameworkCore;
  16. using Microsoft.Extensions.Logging;
  17. namespace Jellyfin.Server.Migrations.Routines;
  18. /// <summary>
  19. /// Migration to move extracted files to the new directories.
  20. /// </summary>
  21. [JellyfinMigration("2025-04-21T00:00:00", nameof(MigrateKeyframeData))]
  22. public class MigrateKeyframeData : IDatabaseMigrationRoutine
  23. {
  24. private readonly IStartupLogger _logger;
  25. private readonly IApplicationPaths _appPaths;
  26. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  27. private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  28. /// <summary>
  29. /// Initializes a new instance of the <see cref="MigrateKeyframeData"/> class.
  30. /// </summary>
  31. /// <param name="startupLogger">The startup logger for Startup UI intigration.</param>
  32. /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
  33. /// <param name="dbProvider">The EFCore db factory.</param>
  34. public MigrateKeyframeData(
  35. IStartupLogger startupLogger,
  36. IApplicationPaths appPaths,
  37. IDbContextFactory<JellyfinDbContext> dbProvider)
  38. {
  39. _logger = startupLogger;
  40. _appPaths = appPaths;
  41. _dbProvider = dbProvider;
  42. }
  43. private string KeyframeCachePath => Path.Combine(_appPaths.DataPath, "keyframes");
  44. /// <inheritdoc />
  45. public void Perform()
  46. {
  47. const int Limit = 5000;
  48. int itemCount = 0, offset = 0;
  49. var sw = Stopwatch.StartNew();
  50. using var context = _dbProvider.CreateDbContext();
  51. var baseQuery = context.BaseItems.Where(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder).OrderBy(e => e.Id);
  52. var records = baseQuery.Count();
  53. _logger.LogInformation("Checking {Count} items for importable keyframe data.", records);
  54. context.KeyframeData.ExecuteDelete();
  55. using var transaction = context.Database.BeginTransaction();
  56. do
  57. {
  58. var results = baseQuery.Skip(offset).Take(Limit).Select(b => new Tuple<Guid, string?>(b.Id, b.Path)).ToList();
  59. foreach (var result in results)
  60. {
  61. if (TryGetKeyframeData(result.Item1, result.Item2, out var data))
  62. {
  63. itemCount++;
  64. context.KeyframeData.Add(data);
  65. }
  66. }
  67. offset += Limit;
  68. if (offset > records)
  69. {
  70. offset = records;
  71. }
  72. _logger.LogInformation("Checked: {Count} - Imported: {Items} - Time: {Time}", offset, itemCount, sw.Elapsed);
  73. } while (offset < records);
  74. context.SaveChanges();
  75. transaction.Commit();
  76. _logger.LogInformation("Imported keyframes for {Count} items in {Time}", itemCount, sw.Elapsed);
  77. if (Directory.Exists(KeyframeCachePath))
  78. {
  79. Directory.Delete(KeyframeCachePath, true);
  80. }
  81. }
  82. private bool TryGetKeyframeData(Guid id, string? path, [NotNullWhen(true)] out KeyframeData? data)
  83. {
  84. data = null;
  85. if (!string.IsNullOrEmpty(path))
  86. {
  87. var cachePath = GetCachePath(KeyframeCachePath, path);
  88. if (TryReadFromCache(cachePath, out var keyframeData))
  89. {
  90. data = new()
  91. {
  92. ItemId = id,
  93. KeyframeTicks = keyframeData.KeyframeTicks.ToList(),
  94. TotalDuration = keyframeData.TotalDuration
  95. };
  96. return true;
  97. }
  98. }
  99. return false;
  100. }
  101. private string? GetCachePath(string keyframeCachePath, string filePath)
  102. {
  103. DateTime? lastWriteTimeUtc;
  104. try
  105. {
  106. lastWriteTimeUtc = File.GetLastWriteTimeUtc(filePath);
  107. }
  108. catch (IOException e)
  109. {
  110. _logger.LogDebug("Skipping {Path}: {Exception}", filePath, e.Message);
  111. return null;
  112. }
  113. ReadOnlySpan<char> filename = (filePath + "_" + lastWriteTimeUtc.Value.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5() + ".json";
  114. var prefix = filename[..1];
  115. return Path.Join(keyframeCachePath, prefix, filename);
  116. }
  117. private static bool TryReadFromCache(string? cachePath, [NotNullWhen(true)] out MediaEncoding.Keyframes.KeyframeData? cachedResult)
  118. {
  119. if (File.Exists(cachePath))
  120. {
  121. var bytes = File.ReadAllBytes(cachePath);
  122. cachedResult = JsonSerializer.Deserialize<MediaEncoding.Keyframes.KeyframeData>(bytes, _jsonOptions);
  123. return cachedResult is not null;
  124. }
  125. cachedResult = null;
  126. return false;
  127. }
  128. }