FixDates.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. var context = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
  40. await using (context.ConfigureAwait(false))
  41. {
  42. var sw = Stopwatch.StartNew();
  43. await FixBaseItemsAsync(context, sw, cancellationToken).ConfigureAwait(false);
  44. sw.Reset();
  45. await FixChaptersAsync(context, sw, cancellationToken).ConfigureAwait(false);
  46. sw.Reset();
  47. await FixBaseItemImageInfos(context, sw, cancellationToken).ConfigureAwait(false);
  48. }
  49. }
  50. }
  51. private async Task FixBaseItemsAsync(JellyfinDbContext context, Stopwatch sw, CancellationToken cancellationToken)
  52. {
  53. int itemCount = 0;
  54. var baseQuery = context.BaseItems.OrderBy(e => e.Id);
  55. var records = baseQuery.Count();
  56. _logger.LogInformation("Fixing dates for {Count} BaseItems.", records);
  57. sw.Start();
  58. await foreach (var result in context.BaseItems.OrderBy(e => e.Id)
  59. .WithPartitionProgress(
  60. (partition) =>
  61. _logger.LogInformation(
  62. "Processing BaseItems batch {BatchNumber} ({ProcessedSoFar}/{TotalRecords}) - Time: {ElapsedTime}",
  63. partition + 1,
  64. Math.Min((partition + 1) * PageSize, records),
  65. records,
  66. sw.Elapsed))
  67. .PartitionEagerAsync(PageSize, cancellationToken)
  68. .WithCancellation(cancellationToken)
  69. .ConfigureAwait(false))
  70. {
  71. result.DateCreated = ToUniversalTime(result.DateCreated);
  72. result.DateLastMediaAdded = ToUniversalTime(result.DateLastMediaAdded);
  73. result.DateLastRefreshed = ToUniversalTime(result.DateLastRefreshed);
  74. result.DateLastSaved = ToUniversalTime(result.DateLastSaved);
  75. result.DateModified = ToUniversalTime(result.DateModified);
  76. itemCount++;
  77. }
  78. var saveCount = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
  79. _logger.LogInformation("BaseItems: Processed {ItemCount} items, saved {SaveCount} changes in {ElapsedTime}", itemCount, saveCount, sw.Elapsed);
  80. }
  81. private async Task FixChaptersAsync(JellyfinDbContext context, Stopwatch sw, CancellationToken cancellationToken)
  82. {
  83. int itemCount = 0;
  84. var baseQuery = context.Chapters;
  85. var records = baseQuery.Count();
  86. _logger.LogInformation("Fixing dates for {Count} Chapters.", records);
  87. sw.Start();
  88. await foreach (var result in context.Chapters.OrderBy(e => e.ItemId)
  89. .WithPartitionProgress(
  90. (partition) =>
  91. _logger.LogInformation(
  92. "Processing Chapter batch {BatchNumber} ({ProcessedSoFar}/{TotalRecords}) - Time: {ElapsedTime}",
  93. partition + 1,
  94. Math.Min((partition + 1) * PageSize, records),
  95. records,
  96. sw.Elapsed))
  97. .PartitionEagerAsync(PageSize, cancellationToken)
  98. .WithCancellation(cancellationToken)
  99. .ConfigureAwait(false))
  100. {
  101. result.ImageDateModified = ToUniversalTime(result.ImageDateModified, true);
  102. itemCount++;
  103. }
  104. var saveCount = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
  105. _logger.LogInformation("Chapters: Processed {ItemCount} items, saved {SaveCount} changes in {ElapsedTime}", itemCount, saveCount, sw.Elapsed);
  106. }
  107. private async Task FixBaseItemImageInfos(JellyfinDbContext context, Stopwatch sw, CancellationToken cancellationToken)
  108. {
  109. int itemCount = 0;
  110. var baseQuery = context.BaseItemImageInfos;
  111. var records = baseQuery.Count();
  112. _logger.LogInformation("Fixing dates for {Count} BaseItemImageInfos.", records);
  113. sw.Start();
  114. await foreach (var result in context.BaseItemImageInfos.OrderBy(e => e.Id)
  115. .WithPartitionProgress(
  116. (partition) =>
  117. _logger.LogInformation(
  118. "Processing BaseItemImageInfos batch {BatchNumber} ({ProcessedSoFar}/{TotalRecords}) - Time: {ElapsedTime}",
  119. partition + 1,
  120. Math.Min((partition + 1) * PageSize, records),
  121. records,
  122. sw.Elapsed))
  123. .PartitionEagerAsync(PageSize, cancellationToken)
  124. .WithCancellation(cancellationToken)
  125. .ConfigureAwait(false))
  126. {
  127. result.DateModified = ToUniversalTime(result.DateModified);
  128. itemCount++;
  129. }
  130. var saveCount = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
  131. _logger.LogInformation("BaseItemImageInfos: Processed {ItemCount} items, saved {SaveCount} changes in {ElapsedTime}", itemCount, saveCount, sw.Elapsed);
  132. }
  133. private DateTime? ToUniversalTime(DateTime? dateTime, bool isUTC = false)
  134. {
  135. if (dateTime is null)
  136. {
  137. return null;
  138. }
  139. if (dateTime.Value.Year == 1 && dateTime.Value.Month == 1 && dateTime.Value.Day == 1)
  140. {
  141. return null;
  142. }
  143. if (dateTime.Value.Kind == DateTimeKind.Utc || isUTC)
  144. {
  145. return dateTime.Value;
  146. }
  147. return dateTime.Value.ToUniversalTime();
  148. }
  149. }