< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MigrateLibraryUserData
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/MigrateLibraryUserData.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 4
Coverable lines: 4
Total lines: 123
Line coverage: 0%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/MigrateLibraryUserData.cs

#LineLine coverage
 1#pragma warning disable RS0030 // Do not use banned APIs
 2
 3using System;
 4using System.Collections.Generic;
 5using System.IO;
 6using System.Linq;
 7using System.Threading;
 8using System.Threading.Tasks;
 9using Emby.Server.Implementations.Data;
 10using Jellyfin.Database.Implementations;
 11using Jellyfin.Database.Implementations.Entities;
 12using Jellyfin.Server.Implementations.Item;
 13using Jellyfin.Server.ServerSetupApp;
 14using MediaBrowser.Controller;
 15using Microsoft.Data.Sqlite;
 16using Microsoft.EntityFrameworkCore;
 17using Microsoft.Extensions.Logging;
 18
 19namespace Jellyfin.Server.Migrations.Routines;
 20
 21[JellyfinMigration("2025-06-18T01:00:00", nameof(MigrateLibraryUserData))]
 22[JellyfinMigrationBackup(JellyfinDb = true)]
 23internal class MigrateLibraryUserData : IAsyncMigrationRoutine
 24{
 25    private const string DbFilename = "library.db.old";
 26
 27    private readonly IStartupLogger _logger;
 28    private readonly IServerApplicationPaths _paths;
 29    private readonly IDbContextFactory<JellyfinDbContext> _provider;
 30
 31    public MigrateLibraryUserData(
 32            IStartupLogger<MigrateLibraryDb> startupLogger,
 33            IDbContextFactory<JellyfinDbContext> provider,
 34            IServerApplicationPaths paths)
 35    {
 036        _logger = startupLogger;
 037        _provider = provider;
 038        _paths = paths;
 039    }
 40
 41    public async Task PerformAsync(CancellationToken cancellationToken)
 42    {
 43        _logger.LogInformation("Migrating the userdata from library.db.old may take a while, do not stop Jellyfin.");
 44
 45        var dataPath = _paths.DataPath;
 46        var libraryDbPath = Path.Combine(dataPath, DbFilename);
 47        if (!File.Exists(libraryDbPath))
 48        {
 49            _logger.LogError("Cannot migrate userdata from {LibraryDb} as it does not exist. This migration expects the 
 50            return;
 51        }
 52
 53        var dbContext = await _provider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
 54        await using (dbContext.ConfigureAwait(false))
 55        {
 56            if (!await dbContext.BaseItems.AnyAsync(e => e.Id == BaseItemRepository.PlaceholderId, cancellationToken).Co
 57            {
 58                // the placeholder baseitem has been deleted by the librarydb migration so we need to readd it.
 59                await dbContext.BaseItems.AddAsync(
 60                    new Database.Implementations.Entities.BaseItemEntity()
 61                    {
 62                        Id = BaseItemRepository.PlaceholderId,
 63                        Type = "PLACEHOLDER",
 64                        Name = "This is a placeholder item for UserData that has been detacted from its original item"
 65                    },
 66                    cancellationToken)
 67                    .ConfigureAwait(false);
 68                await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
 69            }
 70
 71            var users = dbContext.Users.AsNoTracking().ToArray();
 72            var userIdBlacklist = new HashSet<int>();
 73            using var connection = new SqliteConnection($"Filename={libraryDbPath};Mode=ReadOnly");
 74            var retentionDate = DateTime.UtcNow;
 75
 76            var queryResult = connection.Query(
 77"""
 78    SELECT key, userId, rating, played, playCount, isFavorite, playbackPositionTicks, lastPlayedDate, AudioStreamIndex, 
 79
 80    WHERE NOT EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.UserDataKey = UserDatas.key)
 81""");
 82
 83            var importedUserData = new Dictionary<Guid, List<UserData>>();
 84            foreach (var entity in queryResult)
 85            {
 86                var userData = MigrateLibraryDb.GetUserData(users, entity, userIdBlacklist, _logger);
 87                if (userData is null)
 88                {
 89                    var userDataId = entity.GetString(0);
 90                    var internalUserId = entity.GetInt32(1);
 91
 92                    if (!userIdBlacklist.Contains(internalUserId))
 93                    {
 94                        _logger.LogError("Was not able to migrate user data with key {0} because its id {InternalId} doe
 95                        userIdBlacklist.Add(internalUserId);
 96                    }
 97
 98                    continue;
 99                }
 100
 101                var ogId = userData.ItemId;
 102                userData.ItemId = BaseItemRepository.PlaceholderId;
 103                userData.RetentionDate = retentionDate;
 104                if (!importedUserData.TryGetValue(ogId, out var importUserData))
 105                {
 106                    importUserData = [];
 107                    importedUserData[ogId] = importUserData;
 108                }
 109
 110                importUserData.Add(userData);
 111            }
 112
 113            foreach (var item in importedUserData)
 114            {
 115                await dbContext.UserData.Where(e => e.ItemId == item.Key).ExecuteDeleteAsync(cancellationToken).Configur
 116                dbContext.UserData.AddRange(item.Value.DistinctBy(e => e.CustomDataKey)); // old userdata can have fucke
 117            }
 118
 119            _logger.LogInformation("Try saving {NewSaved} UserData entries.", dbContext.UserData.Local.Count);
 120            await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
 121        }
 122    }
 123}