aboutsummaryrefslogtreecommitdiff
path: root/tests/Jellyfin.Server.Tests/Migrations/RepairAlternateVersionLinksTests.cs
blob: 34eff8a988e17874d2aa4b56404862b6c2db51d0 (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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Database.Implementations.Locking;
using Jellyfin.Database.Providers.Sqlite;
using Jellyfin.Server.Migrations.Routines;
using Jellyfin.Server.ServerSetupApp;
using MediaBrowser.Common.Configuration;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;

namespace Jellyfin.Server.Tests.Migrations;

/// <summary>
/// Covers the repair of the PrimaryVersionId the item queries hide an alternate version by,
/// including the link shapes that would otherwise leave a whole version group hidden.
/// </summary>
public sealed class RepairAlternateVersionLinksTests : IDisposable
{
    private readonly SqliteConnection _connection;
    private readonly DbContextOptions<JellyfinDbContext> _dbOptions;
    private readonly IApplicationPaths _applicationPaths;

    public RepairAlternateVersionLinksTests()
    {
        _applicationPaths = new Mock<IApplicationPaths>().Object;

        // The connection owns the in-memory database, so it stays open for the whole test.
        _connection = new SqliteConnection("Data Source=:memory:");
        _connection.Open();

        _dbOptions = new DbContextOptionsBuilder<JellyfinDbContext>()
            .UseSqlite(_connection)
            .Options;

        using var context = CreateDbContext();
        context.Database.EnsureCreated();
    }

    [Fact]
    public async Task PerformAsync_VersionLinkedToPrimary_PointsItAtThePrimary()
    {
        var primaryId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
        var versionId = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb");

        Seed(
            [(primaryId, null), (versionId, null)],
            [(primaryId, versionId)]);

        await PerformAsync();

        using var context = CreateDbContext();
        AssertIsVersionOf(context, versionId, primaryId);
        AssertIsPrimary(context, primaryId);
    }

    [Fact]
    public async Task PerformAsync_VideosLinkedAsEachOthersVersion_KeepsOneOfThemVisible()
    {
        var firstId = Guid.Parse("cccccccc-cccc-cccc-cccc-cccccccccccc");
        var secondId = Guid.Parse("dddddddd-dddd-dddd-dddd-dddddddddddd");

        // Each one claims the other as its version, so pointing both at their link would hide the
        // group in its entirety.
        Seed(
            [(firstId, null), (secondId, null)],
            [(firstId, secondId), (secondId, firstId)]);

        await PerformAsync();

        using var context = CreateDbContext();
        var first = Get(context, firstId);
        var second = Get(context, secondId);

        var primary = first.PrimaryVersionId is null ? first : second;
        var version = first.PrimaryVersionId is null ? second : first;

        Assert.Null(primary.PrimaryVersionId);
        AssertIsPrimary(context, primary.Id);
        AssertIsVersionOf(context, version.Id, primary.Id);
    }

    [Fact]
    public async Task PerformAsync_PrimaryStillPointingAtItsOwnVersion_ClearsTheStalePrimary()
    {
        var primaryId = Guid.Parse("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee");
        var versionId = Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff");

        // The primary was promoted over the version it now heads, but kept the pointer to it: the
        // repair below would point the version back and leave both hidden.
        Seed(
            [(primaryId, versionId), (versionId, null)],
            [(primaryId, versionId)]);

        await PerformAsync();

        using var context = CreateDbContext();
        AssertIsPrimary(context, primaryId);
        AssertIsVersionOf(context, versionId, primaryId);
    }

    [Fact]
    public async Task PerformAsync_ChainedLinks_PointsEveryVersionAtTheHeadOfTheChain()
    {
        var headId = Guid.Parse("11111111-1111-1111-1111-111111111111");
        var middleId = Guid.Parse("22222222-2222-2222-2222-222222222222");
        var tailId = Guid.Parse("33333333-3333-3333-3333-333333333333");

        // The middle one is a version of the head and a primary of the tail at the same time.
        Seed(
            [(headId, null), (middleId, null), (tailId, null)],
            [(headId, middleId), (middleId, tailId)]);

        await PerformAsync();

        using var context = CreateDbContext();
        AssertIsPrimary(context, headId);
        AssertIsVersionOf(context, middleId, headId);
        AssertIsVersionOf(context, tailId, headId);
    }

    [Fact]
    public async Task PerformAsync_VersionLinkedToItself_LeavesItVisible()
    {
        var itemId = Guid.Parse("44444444-4444-4444-4444-444444444444");

        Seed([(itemId, null)], [(itemId, itemId)]);

        await PerformAsync();

        using var context = CreateDbContext();
        Assert.Null(Get(context, itemId).PrimaryVersionId);
    }

    public void Dispose()
    {
        _connection.Dispose();
    }

    private static void AssertIsPrimary(JellyfinDbContext context, Guid id)
    {
        var item = Get(context, id);
        Assert.Null(item.PrimaryVersionId);
        Assert.Equal(id.ToString("N", CultureInfo.InvariantCulture), item.PresentationUniqueKey);
    }

    private static void AssertIsVersionOf(JellyfinDbContext context, Guid id, Guid primaryId)
    {
        var item = Get(context, id);
        Assert.Equal(primaryId, item.PrimaryVersionId);

        // Presentation-key grouping has to collapse the version onto its primary as well.
        Assert.Equal(primaryId.ToString("N", CultureInfo.InvariantCulture), item.PresentationUniqueKey);
    }

    private static BaseItemEntity Get(JellyfinDbContext context, Guid id)
        => context.BaseItems.AsNoTracking().First(e => e.Id.Equals(id));

    private JellyfinDbContext CreateDbContext() => new(
        _dbOptions,
        NullLogger<JellyfinDbContext>.Instance,
        new SqliteDatabaseProvider(_applicationPaths, NullLogger<SqliteDatabaseProvider>.Instance),
        new NoLockBehavior(NullLogger<NoLockBehavior>.Instance));

    private void Seed(
        (Guid Id, Guid? PrimaryVersionId)[] items,
        (Guid ParentId, Guid ChildId)[] links)
    {
        using var context = CreateDbContext();

        foreach (var (id, primaryVersionId) in items)
        {
            context.BaseItems.Add(new BaseItemEntity
            {
                Id = id,
                Type = "MediaBrowser.Controller.Entities.Movies.Movie",
                Name = "Movie",
                PrimaryVersionId = primaryVersionId,
                PresentationUniqueKey = (primaryVersionId ?? id).ToString("N", CultureInfo.InvariantCulture)
            });
        }

        foreach (var (parentId, childId) in links)
        {
            context.LinkedChildren.Add(new LinkedChildEntity
            {
                ParentId = parentId,
                ChildId = childId,
                ChildType = LinkedChildType.LinkedAlternateVersion
            });
        }

        context.SaveChanges();
    }

    private Task PerformAsync()
    {
        var factory = new Mock<IDbContextFactory<JellyfinDbContext>>();
        factory.Setup(f => f.CreateDbContext()).Returns(CreateDbContext);
        factory.Setup(f => f.CreateDbContextAsync(It.IsAny<CancellationToken>()))
            .ReturnsAsync(CreateDbContext);

        var migration = new RepairAlternateVersionLinks(
            new StartupLogger<RepairAlternateVersionLinks>(NullLogger<RepairAlternateVersionLinks>.Instance),
            factory.Object);

        return migration.PerformAsync(CancellationToken.None);
    }
}