2
0

MigrateKeyframeData.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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 MediaBrowser.Common.Configuration;
  13. using MediaBrowser.Common.Extensions;
  14. using Microsoft.EntityFrameworkCore;
  15. using Microsoft.Extensions.Logging;
  16. namespace Jellyfin.Server.Migrations.Routines;
  17. /// <summary>
  18. /// Migration to move extracted files to the new directories.
  19. /// </summary>
  20. public class MigrateKeyframeData : IDatabaseMigrationRoutine
  21. {
  22. private readonly ILogger<MigrateKeyframeData> _logger;
  23. private readonly IApplicationPaths _appPaths;
  24. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  25. private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="MigrateKeyframeData"/> class.
  28. /// </summary>
  29. /// <param name="logger">The logger.</param>
  30. /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
  31. /// <param name="dbProvider">The EFCore db factory.</param>
  32. public MigrateKeyframeData(
  33. ILogger<MigrateKeyframeData> logger,
  34. IApplicationPaths appPaths,
  35. IDbContextFactory<JellyfinDbContext> dbProvider)
  36. {
  37. _logger = logger;
  38. _appPaths = appPaths;
  39. _dbProvider = dbProvider;
  40. }
  41. private string KeyframeCachePath => Path.Combine(_appPaths.DataPath, "keyframes");
  42. /// <inheritdoc />
  43. public Guid Id => new("EA4bCAE1-09A4-428E-9B90-4B4FD2EA1B24");
  44. /// <inheritdoc />
  45. public string Name => "MigrateKeyframeData";
  46. /// <inheritdoc />
  47. public bool PerformOnNewInstall => false;
  48. /// <inheritdoc />
  49. public void Perform()
  50. {
  51. const int Limit = 5000;
  52. int itemCount = 0, offset = 0;
  53. var sw = Stopwatch.StartNew();
  54. using var context = _dbProvider.CreateDbContext();
  55. var baseQuery = context.BaseItems.Where(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b.IsFolder).OrderBy(e => e.Id);
  56. var records = baseQuery.Count();
  57. _logger.LogInformation("Checking {Count} items for importable keyframe data.", records);
  58. context.KeyframeData.ExecuteDelete();
  59. using var transaction = context.Database.BeginTransaction();
  60. do
  61. {
  62. var results = baseQuery.Skip(offset).Take(Limit).Select(b => new Tuple<Guid, string?>(b.Id, b.Path)).ToList();
  63. foreach (var result in results)
  64. {
  65. if (TryGetKeyframeData(result.Item1, result.Item2, out var data))
  66. {
  67. itemCount++;
  68. context.KeyframeData.Add(data);
  69. }
  70. }
  71. offset += Limit;
  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. }