aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Server/Migrations/Routines/FixDates.cs
blob: f112502b9f42df5211aa047377318f332cc27f34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations;
using Jellyfin.Server.ServerSetupApp;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Jellyfin.Server.Migrations.Routines;

/// <summary>
/// Migration to fix dates saved in the database to always be UTC.
/// </summary>
[JellyfinMigration("2025-06-20T18:00:00", nameof(FixDates))]
public class FixDates : IAsyncMigrationRoutine
{
    private const int PageSize = 5000;

    private readonly ILogger _logger;
    private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;

    /// <summary>
    /// Initializes a new instance of the <see cref="FixDates"/> class.
    /// </summary>
    /// <param name="logger">The logger.</param>
    /// <param name="startupLogger">The startup logger for Startup UI integration.</param>
    /// <param name="dbProvider">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
    public FixDates(
        ILogger<FixDates> logger,
        IStartupLogger<FixDates> startupLogger,
        IDbContextFactory<JellyfinDbContext> dbProvider)
    {
        _logger = startupLogger.With(logger);
        _dbProvider = dbProvider;
    }

    /// <inheritdoc />
    public async Task PerformAsync(CancellationToken cancellationToken)
    {
        if (!TimeZoneInfo.Local.Equals(TimeZoneInfo.Utc))
        {
            using var context = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
            var sw = Stopwatch.StartNew();

            await FixBaseItemsAsync(context, sw, cancellationToken).ConfigureAwait(false);
            sw.Reset();
            await FixChaptersAsync(context, sw, cancellationToken).ConfigureAwait(false);
            sw.Reset();
            await FixBaseItemImageInfos(context, sw, cancellationToken).ConfigureAwait(false);
        }
    }

    private async Task FixBaseItemsAsync(JellyfinDbContext context, Stopwatch sw, CancellationToken cancellationToken)
    {
        int itemCount = 0;

        var baseQuery = context.BaseItems.OrderBy(e => e.Id);
        var records = baseQuery.Count();
        _logger.LogInformation("Fixing dates for {Count} BaseItems.", records);

        sw.Start();
        await foreach (var result in context.BaseItems.OrderBy(e => e.Id)
                        .WithPartitionProgress(
                            (partition) =>
                                _logger.LogInformation(
                                    "Processing BaseItems batch {BatchNumber} ({ProcessedSoFar}/{TotalRecords}) - Time: {ElapsedTime}",
                                    partition + 1,
                                    Math.Min((partition + 1) * PageSize, records),
                                    records,
                                    sw.Elapsed))
                        .PartitionEagerAsync(PageSize, cancellationToken)
                        .WithCancellation(cancellationToken)
                        .ConfigureAwait(false))
        {
            result.DateCreated = ToUniversalTime(result.DateCreated);
            result.DateLastMediaAdded = ToUniversalTime(result.DateLastMediaAdded);
            result.DateLastRefreshed = ToUniversalTime(result.DateLastRefreshed);
            result.DateLastSaved = ToUniversalTime(result.DateLastSaved);
            result.DateModified = ToUniversalTime(result.DateModified);
            itemCount++;
        }

        var saveCount = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
        _logger.LogInformation("BaseItems: Processed {ItemCount} items, saved {SaveCount} changes in {ElapsedTime}", itemCount, saveCount, sw.Elapsed);
    }

    private async Task FixChaptersAsync(JellyfinDbContext context, Stopwatch sw, CancellationToken cancellationToken)
    {
        int itemCount = 0;

        var baseQuery = context.Chapters;
        var records = baseQuery.Count();
        _logger.LogInformation("Fixing dates for {Count} Chapters.", records);

        sw.Start();
        await foreach (var result in context.Chapters.OrderBy(e => e.ItemId)
                        .WithPartitionProgress(
                            (partition) =>
                                _logger.LogInformation(
                                    "Processing Chapter batch {BatchNumber} ({ProcessedSoFar}/{TotalRecords}) - Time: {ElapsedTime}",
                                    partition + 1,
                                    Math.Min((partition + 1) * PageSize, records),
                                    records,
                                    sw.Elapsed))
                        .PartitionEagerAsync(PageSize, cancellationToken)
                        .WithCancellation(cancellationToken)
                        .ConfigureAwait(false))
        {
            result.ImageDateModified = ToUniversalTime(result.ImageDateModified, true);
            itemCount++;
        }

        var saveCount = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
        _logger.LogInformation("Chapters: Processed {ItemCount} items, saved {SaveCount} changes in {ElapsedTime}", itemCount, saveCount, sw.Elapsed);
    }

    private async Task FixBaseItemImageInfos(JellyfinDbContext context, Stopwatch sw, CancellationToken cancellationToken)
    {
        int itemCount = 0;

        var baseQuery = context.BaseItemImageInfos;
        var records = baseQuery.Count();
        _logger.LogInformation("Fixing dates for {Count} BaseItemImageInfos.", records);

        sw.Start();
        await foreach (var result in context.BaseItemImageInfos.OrderBy(e => e.Id)
                        .WithPartitionProgress(
                            (partition) =>
                                _logger.LogInformation(
                                    "Processing BaseItemImageInfos batch {BatchNumber} ({ProcessedSoFar}/{TotalRecords}) - Time: {ElapsedTime}",
                                    partition + 1,
                                    Math.Min((partition + 1) * PageSize, records),
                                    records,
                                    sw.Elapsed))
                        .PartitionEagerAsync(PageSize, cancellationToken)
                        .WithCancellation(cancellationToken)
                        .ConfigureAwait(false))
        {
            result.DateModified = ToUniversalTime(result.DateModified);
            itemCount++;
        }

        var saveCount = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
        _logger.LogInformation("BaseItemImageInfos: Processed {ItemCount} items, saved {SaveCount} changes in {ElapsedTime}", itemCount, saveCount, sw.Elapsed);
    }

    private DateTime? ToUniversalTime(DateTime? dateTime, bool isUTC = false)
    {
        if (dateTime is null)
        {
            return null;
        }

        if (dateTime.Value.Year == 1 && dateTime.Value.Month == 1 && dateTime.Value.Day == 1)
        {
            return null;
        }

        if (dateTime.Value.Kind == DateTimeKind.Utc || isUTC)
        {
            return dateTime.Value;
        }

        return dateTime.Value.ToUniversalTime();
    }
}