FixDates.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Database.Implementations;
  7. using Jellyfin.Server.ServerSetupApp;
  8. using Microsoft.EntityFrameworkCore;
  9. using Microsoft.Extensions.Logging;
  10. namespace Jellyfin.Server.Migrations.Routines;
  11. /// <summary>
  12. /// Migration to fix dates saved in the database to always be UTC.
  13. /// </summary>
  14. [JellyfinMigration("2025-06-20T18:00:00", nameof(FixDates))]
  15. public class FixDates : IAsyncMigrationRoutine
  16. {
  17. private const int PageSize = 5000;
  18. private readonly ILogger _logger;
  19. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  20. /// <summary>
  21. /// Initializes a new instance of the <see cref="FixDates"/> class.
  22. /// </summary>
  23. /// <param name="logger">The logger.</param>
  24. /// <param name="startupLogger">The startup logger for Startup UI integration.</param>
  25. /// <param name="dbProvider">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
  26. public FixDates(
  27. ILogger<FixDates> logger,
  28. IStartupLogger<FixDates> startupLogger,
  29. IDbContextFactory<JellyfinDbContext> dbProvider)
  30. {
  31. _logger = startupLogger.With(logger);
  32. _dbProvider = dbProvider;
  33. }
  34. /// <inheritdoc />
  35. public async Task PerformAsync(CancellationToken cancellationToken)
  36. {
  37. if (!TimeZoneInfo.Local.Equals(TimeZoneInfo.Utc))
  38. {
  39. using var context = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
  40. var sw = Stopwatch.StartNew();
  41. await FixBaseItemsAsync(context, sw, cancellationToken).ConfigureAwait(false);
  42. sw.Reset();
  43. await FixChaptersAsync(context, sw, cancellationToken).ConfigureAwait(false);
  44. sw.Reset();
  45. await FixBaseItemImageInfos(context, sw, cancellationToken).ConfigureAwait(false);
  46. }
  47. }
  48. private async Task FixBaseItemsAsync(JellyfinDbContext context, Stopwatch sw, CancellationToken cancellationToken)
  49. {
  50. int itemCount = 0;
  51. var baseQuery = context.BaseItems.OrderBy(e => e.Id);
  52. var records = baseQuery.Count();
  53. _logger.LogInformation("Fixing dates for {Count} BaseItems.", records);
  54. sw.Start();
  55. await foreach (var result in context.BaseItems.OrderBy(e => e.Id)
  56. .WithPartitionProgress(
  57. (partition) =>
  58. _logger.LogInformation(
  59. "Processing BaseItems batch {BatchNumber} ({ProcessedSoFar}/{TotalRecords}) - Time: {ElapsedTime}",
  60. partition + 1,
  61. Math.Min((partition + 1) * PageSize, records),
  62. records,
  63. sw.Elapsed))
  64. .PartitionEagerAsync(PageSize, cancellationToken)
  65. .WithCancellation(cancellationToken)
  66. .ConfigureAwait(false))
  67. {
  68. result.DateCreated = ToUniversalTime(result.DateCreated);
  69. result.DateLastMediaAdded = ToUniversalTime(result.DateLastMediaAdded);
  70. result.DateLastRefreshed = ToUniversalTime(result.DateLastRefreshed);
  71. result.DateLastSaved = ToUniversalTime(result.DateLastSaved);
  72. result.DateModified = ToUniversalTime(result.DateModified);
  73. itemCount++;
  74. }
  75. var saveCount = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
  76. _logger.LogInformation("BaseItems: Processed {ItemCount} items, saved {SaveCount} changes in {ElapsedTime}", itemCount, saveCount, sw.Elapsed);
  77. }
  78. private async Task FixChaptersAsync(JellyfinDbContext context, Stopwatch sw, CancellationToken cancellationToken)
  79. {
  80. int itemCount = 0;
  81. var baseQuery = context.Chapters;
  82. var records = baseQuery.Count();
  83. _logger.LogInformation("Fixing dates for {Count} Chapters.", records);
  84. sw.Start();
  85. await foreach (var result in context.Chapters.OrderBy(e => e.ItemId)
  86. .WithPartitionProgress(
  87. (partition) =>
  88. _logger.LogInformation(
  89. "Processing Chapter batch {BatchNumber} ({ProcessedSoFar}/{TotalRecords}) - Time: {ElapsedTime}",
  90. partition + 1,
  91. Math.Min((partition + 1) * PageSize, records),
  92. records,
  93. sw.Elapsed))
  94. .PartitionEagerAsync(PageSize, cancellationToken)
  95. .WithCancellation(cancellationToken)
  96. .ConfigureAwait(false))
  97. {
  98. result.ImageDateModified = ToUniversalTime(result.ImageDateModified, true);
  99. itemCount++;
  100. }
  101. var saveCount = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
  102. _logger.LogInformation("Chapters: Processed {ItemCount} items, saved {SaveCount} changes in {ElapsedTime}", itemCount, saveCount, sw.Elapsed);
  103. }
  104. private async Task FixBaseItemImageInfos(JellyfinDbContext context, Stopwatch sw, CancellationToken cancellationToken)
  105. {
  106. int itemCount = 0;
  107. var baseQuery = context.BaseItemImageInfos;
  108. var records = baseQuery.Count();
  109. _logger.LogInformation("Fixing dates for {Count} BaseItemImageInfos.", records);
  110. sw.Start();
  111. await foreach (var result in context.BaseItemImageInfos.OrderBy(e => e.Id)
  112. .WithPartitionProgress(
  113. (partition) =>
  114. _logger.LogInformation(
  115. "Processing BaseItemImageInfos batch {BatchNumber} ({ProcessedSoFar}/{TotalRecords}) - Time: {ElapsedTime}",
  116. partition + 1,
  117. Math.Min((partition + 1) * PageSize, records),
  118. records,
  119. sw.Elapsed))
  120. .PartitionEagerAsync(PageSize, cancellationToken)
  121. .WithCancellation(cancellationToken)
  122. .ConfigureAwait(false))
  123. {
  124. result.DateModified = ToUniversalTime(result.DateModified);
  125. itemCount++;
  126. }
  127. var saveCount = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
  128. _logger.LogInformation("BaseItemImageInfos: Processed {ItemCount} items, saved {SaveCount} changes in {ElapsedTime}", itemCount, saveCount, sw.Elapsed);
  129. }
  130. private DateTime? ToUniversalTime(DateTime? dateTime, bool isUTC = false)
  131. {
  132. if (dateTime is null)
  133. {
  134. return null;
  135. }
  136. if (dateTime.Value.Year == 1 && dateTime.Value.Month == 1 && dateTime.Value.Day == 1)
  137. {
  138. return null;
  139. }
  140. if (dateTime.Value.Kind == DateTimeKind.Utc || isUTC)
  141. {
  142. return dateTime.Value;
  143. }
  144. return dateTime.Value.ToUniversalTime();
  145. }
  146. }