< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MigrateAuthenticationDb
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20250420140000_MigrateAuthenticationDb.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 69
Coverable lines: 69
Total lines: 170
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 22
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/67) Branch coverage: 0% (0/22) Total lines: 1627/6/2026 - 12:16:28 AM Line coverage: 0% (0/67) Branch coverage: 0% (0/22) Total lines: 16311/13/2026 - 12:19:51 AM Line coverage: 0% (0/69) Branch coverage: 0% (0/22) Total lines: 170 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/67) Branch coverage: 0% (0/22) Total lines: 1627/6/2026 - 12:16:28 AM Line coverage: 0% (0/67) Branch coverage: 0% (0/22) Total lines: 16311/13/2026 - 12:19:51 AM Line coverage: 0% (0/69) Branch coverage: 0% (0/22) Total lines: 170

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
PerformAsync(...)100%210%
PerformCore()0%506220%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20250420140000_MigrateAuthenticationDb.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Globalization;
 4using System.IO;
 5using System.Threading;
 6using System.Threading.Tasks;
 7using Emby.Server.Implementations.Data;
 8using Jellyfin.Database.Implementations;
 9using Jellyfin.Database.Implementations.Entities.Security;
 10using MediaBrowser.Controller;
 11using MediaBrowser.Controller.Library;
 12using Microsoft.Data.Sqlite;
 13using Microsoft.EntityFrameworkCore;
 14using Microsoft.Extensions.Logging;
 15
 16namespace Jellyfin.Server.Migrations.Routines
 17{
 18    /// <summary>
 19    /// A migration that moves data from the authentication database into the new schema.
 20    /// </summary>
 21    [JellyfinMigration("2025-04-20T14:00:00", nameof(MigrateAuthenticationDb), "5BD72F41-E6F3-4F60-90AA-09869ABE0E22")]
 22    public class MigrateAuthenticationDb : IAsyncMigrationRoutine
 23    {
 24        private const string DbFilename = "authentication.db";
 25
 26        private readonly ILogger<MigrateAuthenticationDb> _logger;
 27        private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
 28        private readonly IServerApplicationPaths _appPaths;
 29        private readonly IUserManager _userManager;
 30
 31        /// <summary>
 32        /// Initializes a new instance of the <see cref="MigrateAuthenticationDb"/> class.
 33        /// </summary>
 34        /// <param name="logger">The logger.</param>
 35        /// <param name="dbProvider">The database provider.</param>
 36        /// <param name="appPaths">The server application paths.</param>
 37        /// <param name="userManager">The user manager.</param>
 38        public MigrateAuthenticationDb(
 39            ILogger<MigrateAuthenticationDb> logger,
 40            IDbContextFactory<JellyfinDbContext> dbProvider,
 41            IServerApplicationPaths appPaths,
 42            IUserManager userManager)
 43        {
 044            _logger = logger;
 045            _dbProvider = dbProvider;
 046            _appPaths = appPaths;
 047            _userManager = userManager;
 048        }
 49
 50        /// <inheritdoc />
 51        public Task PerformAsync(CancellationToken cancellationToken)
 52        {
 53            // This routine predates the async interface and has not been ported to async database access yet.
 054            PerformCore();
 055            return Task.CompletedTask;
 56        }
 57
 58        private void PerformCore()
 59        {
 060            var dataPath = _appPaths.DataPath;
 061            var dbFilePath = Path.Combine(dataPath, DbFilename);
 62
 063            if (!File.Exists(dbFilePath))
 64            {
 065                _logger.LogWarning("{Path} doesn't exist, nothing to migrate", dbFilePath);
 066                return;
 67            }
 68
 069            using (var connection = new SqliteConnection($"Filename={dbFilePath}"))
 70            {
 071                connection.Open();
 72
 073                var tableQuery = connection.Query("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='Token
 074                foreach (var row in tableQuery)
 75                {
 076                    if (row.GetInt32(0) == 0)
 77                    {
 078                        _logger.LogWarning("Table 'Tokens' doesn't exist in {Path}, nothing to migrate", dbFilePath);
 079                        return;
 80                    }
 81                }
 82
 083                using var dbContext = _dbProvider.CreateDbContext();
 84
 085                var authenticatedDevices = connection.Query("SELECT * FROM Tokens");
 86
 087                foreach (var row in authenticatedDevices)
 88                {
 089                    var dateCreatedStr = row.GetString(9);
 090                    _ = DateTime.TryParse(dateCreatedStr, CultureInfo.InvariantCulture, out var dateCreated);
 091                    var dateLastActivityStr = row.GetString(10);
 092                    _ = DateTime.TryParse(dateLastActivityStr, CultureInfo.InvariantCulture, out var dateLastActivity);
 93
 094                    if (row.IsDBNull(6))
 95                    {
 096                        dbContext.ApiKeys.Add(new ApiKey(row.GetString(3))
 097                        {
 098                            AccessToken = row.GetString(1),
 099                            DateCreated = dateCreated,
 0100                            DateLastActivity = dateLastActivity
 0101                        });
 102                    }
 103                    else
 104                    {
 0105                        var userId = row.GetGuid(6);
 0106                        var user = _userManager.GetUserById(userId);
 0107                        if (user is null)
 108                        {
 109                            // User doesn't exist, don't bring over the device.
 110                            continue;
 111                        }
 112
 0113                        dbContext.Devices.Add(new Device(
 0114                            userId,
 0115                            row.GetString(3),
 0116                            row.GetString(4),
 0117                            row.GetString(5),
 0118                            row.GetString(2))
 0119                        {
 0120                            AccessToken = row.GetString(1),
 0121                            IsActive = row.GetBoolean(8),
 0122                            DateCreated = dateCreated,
 0123                            DateLastActivity = dateLastActivity
 0124                        });
 125                    }
 126                }
 127
 0128                var deviceOptions = connection.Query("SELECT * FROM Devices");
 0129                var deviceIds = new HashSet<string>();
 0130                foreach (var row in deviceOptions)
 131                {
 0132                    if (row.IsDBNull(2))
 133                    {
 134                        continue;
 135                    }
 136
 0137                    var deviceId = row.GetString(2);
 0138                    if (deviceIds.Contains(deviceId))
 139                    {
 140                        continue;
 141                    }
 142
 0143                    deviceIds.Add(deviceId);
 144
 0145                    dbContext.DeviceOptions.Add(new DeviceOptions(deviceId)
 0146                    {
 0147                        CustomName = row.IsDBNull(1) ? null : row.GetString(1)
 0148                    });
 149                }
 150
 0151                dbContext.SaveChanges();
 152            }
 153
 154            try
 155            {
 0156                File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
 157
 0158                var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
 0159                if (File.Exists(journalPath))
 160                {
 0161                    File.Move(journalPath, Path.Combine(dataPath, DbFilename + ".old-journal"));
 162                }
 0163            }
 0164            catch (IOException e)
 165            {
 0166                _logger.LogError(e, "Error renaming legacy activity log database to 'authentication.db.old'");
 0167            }
 0168        }
 169    }
 170}