< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MigrateDisplayPreferencesDb
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20250420120000_MigrateDisplayPreferencesDb.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 126
Coverable lines: 126
Total lines: 249
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 56
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/124) Branch coverage: 0% (0/56) Total lines: 24211/13/2026 - 12:19:51 AM Line coverage: 0% (0/126) Branch coverage: 0% (0/56) Total lines: 249 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/124) Branch coverage: 0% (0/56) Total lines: 24211/13/2026 - 12:19:51 AM Line coverage: 0% (0/126) Branch coverage: 0% (0/56) Total lines: 249

Coverage delta

Coverage delta 1 -1

Metrics

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

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20250420120000_MigrateDisplayPreferencesDb.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.Linq;
 5using System.Text.Json;
 6using System.Text.Json.Serialization;
 7using System.Threading;
 8using System.Threading.Tasks;
 9using Emby.Server.Implementations.Data;
 10using Jellyfin.Database.Implementations;
 11using Jellyfin.Database.Implementations.Entities;
 12using Jellyfin.Database.Implementations.Enums;
 13using MediaBrowser.Controller;
 14using MediaBrowser.Controller.Library;
 15using MediaBrowser.Model.Dto;
 16using Microsoft.Data.Sqlite;
 17using Microsoft.EntityFrameworkCore;
 18using Microsoft.Extensions.Logging;
 19
 20namespace Jellyfin.Server.Migrations.Routines
 21{
 22    /// <summary>
 23    /// The migration routine for migrating the display preferences database to EF Core.
 24    /// </summary>
 25    [JellyfinMigration("2025-04-20T12:00:00", nameof(MigrateDisplayPreferencesDb), "06387815-C3CC-421F-A888-FB5F9992BEA8
 26    public class MigrateDisplayPreferencesDb : IAsyncMigrationRoutine
 27    {
 28        private const string DbFilename = "displaypreferences.db";
 29
 30        private readonly ILogger<MigrateDisplayPreferencesDb> _logger;
 31        private readonly IServerApplicationPaths _paths;
 32        private readonly IDbContextFactory<JellyfinDbContext> _provider;
 33        private readonly JsonSerializerOptions _jsonOptions;
 34        private readonly IUserManager _userManager;
 35
 36        /// <summary>
 37        /// Initializes a new instance of the <see cref="MigrateDisplayPreferencesDb"/> class.
 38        /// </summary>
 39        /// <param name="logger">The logger.</param>
 40        /// <param name="paths">The server application paths.</param>
 41        /// <param name="provider">The database provider.</param>
 42        /// <param name="userManager">The user manager.</param>
 43        public MigrateDisplayPreferencesDb(
 44            ILogger<MigrateDisplayPreferencesDb> logger,
 45            IServerApplicationPaths paths,
 46            IDbContextFactory<JellyfinDbContext> provider,
 47            IUserManager userManager)
 48        {
 049            _logger = logger;
 050            _paths = paths;
 051            _provider = provider;
 052            _userManager = userManager;
 053            _jsonOptions = new JsonSerializerOptions();
 054            _jsonOptions.Converters.Add(new JsonStringEnumConverter());
 055        }
 56
 57        /// <inheritdoc />
 58        public Task PerformAsync(CancellationToken cancellationToken)
 59        {
 60            // This routine predates the async interface and has not been ported to async database access yet.
 061            PerformCore();
 062            return Task.CompletedTask;
 63        }
 64
 65        private void PerformCore()
 66        {
 067            HomeSectionType[] defaults =
 068            {
 069                HomeSectionType.SmallLibraryTiles,
 070                HomeSectionType.Resume,
 071                HomeSectionType.ResumeAudio,
 072                HomeSectionType.LiveTv,
 073                HomeSectionType.NextUp,
 074                HomeSectionType.LatestMedia,
 075                HomeSectionType.None,
 076            };
 77
 078            var chromecastDict = new Dictionary<string, ChromecastVersion>(StringComparer.OrdinalIgnoreCase)
 079            {
 080                { "stable", ChromecastVersion.Stable },
 081                { "nightly", ChromecastVersion.Unstable },
 082                { "unstable", ChromecastVersion.Unstable }
 083            };
 84
 085            var displayPrefs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
 086            var customDisplayPrefs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
 087            var dbFilePath = Path.Combine(_paths.DataPath, DbFilename);
 88
 089            if (!File.Exists(dbFilePath))
 90            {
 091                _logger.LogWarning("{Path} doesn't exist, nothing to migrate", dbFilePath);
 092                return;
 93            }
 94
 095            using (var connection = new SqliteConnection($"Filename={dbFilePath}"))
 96            {
 097                connection.Open();
 98
 099                var tableQuery = connection.Query("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='userd
 0100                foreach (var row in tableQuery)
 101                {
 0102                    if (row.GetInt32(0) == 0)
 103                    {
 0104                        _logger.LogWarning("Table 'userdisplaypreferences' doesn't exist in {Path}, nothing to migrate",
 0105                        return;
 106                    }
 107                }
 108
 0109                using var dbContext = _provider.CreateDbContext();
 110
 0111                var results = connection.Query("SELECT * FROM userdisplaypreferences");
 0112                foreach (var result in results)
 113                {
 0114                    var dto = JsonSerializer.Deserialize<DisplayPreferencesDto>(result.GetStream(3), _jsonOptions);
 0115                    if (dto is null)
 116                    {
 117                        continue;
 118                    }
 119
 0120                    var itemId = result.GetGuid(1);
 0121                    var dtoUserId = itemId;
 0122                    var client = result.GetString(2);
 0123                    var displayPreferencesKey = $"{dtoUserId}|{itemId}|{client}";
 0124                    if (displayPrefs.Contains(displayPreferencesKey))
 125                    {
 126                        // Duplicate display preference.
 127                        continue;
 128                    }
 129
 0130                    displayPrefs.Add(displayPreferencesKey);
 0131                    var existingUser = _userManager.GetUserById(dtoUserId);
 0132                    if (existingUser is null)
 133                    {
 0134                        _logger.LogWarning("User with ID {UserId} does not exist in the database, skipping migration.", 
 0135                        continue;
 136                    }
 137
 0138                    var chromecastVersion = dto.CustomPrefs.TryGetValue("chromecastVersion", out var version)
 0139                                            && !string.IsNullOrEmpty(version)
 0140                        ? chromecastDict[version]
 0141                        : ChromecastVersion.Stable;
 0142                    dto.CustomPrefs.Remove("chromecastVersion");
 143
 0144                    var displayPreferences = new DisplayPreferences(dtoUserId, itemId, client)
 0145                    {
 0146                        IndexBy = Enum.TryParse<IndexingKind>(dto.IndexBy, true, out var indexBy) ? indexBy : null,
 0147                        ShowBackdrop = dto.ShowBackdrop,
 0148                        ShowSidebar = dto.ShowSidebar,
 0149                        ScrollDirection = dto.ScrollDirection,
 0150                        ChromecastVersion = chromecastVersion,
 0151                        SkipForwardLength = dto.CustomPrefs.TryGetValue("skipForwardLength", out var length) && int.TryP
 0152                            ? skipForwardLength
 0153                            : 30000,
 0154                        SkipBackwardLength = dto.CustomPrefs.TryGetValue("skipBackLength", out length) && int.TryParse(l
 0155                            ? skipBackwardLength
 0156                            : 10000,
 0157                        EnableNextVideoInfoOverlay = !dto.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var 
 0158                        DashboardTheme = dto.CustomPrefs.TryGetValue("dashboardtheme", out var theme) ? theme : string.E
 0159                        TvHome = dto.CustomPrefs.TryGetValue("tvhome", out var home) ? home : string.Empty
 0160                    };
 161
 0162                    dto.CustomPrefs.Remove("skipForwardLength");
 0163                    dto.CustomPrefs.Remove("skipBackLength");
 0164                    dto.CustomPrefs.Remove("enableNextVideoInfoOverlay");
 0165                    dto.CustomPrefs.Remove("dashboardtheme");
 0166                    dto.CustomPrefs.Remove("tvhome");
 167
 0168                    for (int i = 0; i < 7; i++)
 169                    {
 0170                        var key = "homesection" + i;
 0171                        dto.CustomPrefs.TryGetValue(key, out var homeSection);
 172
 0173                        displayPreferences.HomeSections.Add(new HomeSection
 0174                        {
 0175                            Order = i,
 0176                            Type = Enum.TryParse<HomeSectionType>(homeSection, true, out var type) ? type : defaults[i]
 0177                        });
 178
 0179                        dto.CustomPrefs.Remove(key);
 180                    }
 181
 0182                    var defaultLibraryPrefs = new ItemDisplayPreferences(displayPreferences.UserId, Guid.Empty, displayP
 0183                    {
 0184                        SortBy = dto.SortBy ?? "SortName",
 0185                        SortOrder = dto.SortOrder,
 0186                        RememberIndexing = dto.RememberIndexing,
 0187                        RememberSorting = dto.RememberSorting,
 0188                    };
 189
 0190                    dbContext.Add(defaultLibraryPrefs);
 191
 0192                    foreach (var key in dto.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.Or
 193                    {
 0194                        if (!Guid.TryParse(key.AsSpan().Slice("landing-".Length), out var landingItemId))
 195                        {
 196                            continue;
 197                        }
 198
 0199                        var libraryDisplayPreferences = new ItemDisplayPreferences(displayPreferences.UserId, landingIte
 0200                        {
 0201                            SortBy = dto.SortBy ?? "SortName",
 0202                            SortOrder = dto.SortOrder,
 0203                            RememberIndexing = dto.RememberIndexing,
 0204                            RememberSorting = dto.RememberSorting,
 0205                        };
 206
 0207                        if (Enum.TryParse<ViewType>(dto.ViewType, true, out var viewType))
 208                        {
 0209                            libraryDisplayPreferences.ViewType = viewType;
 210                        }
 211
 0212                        dto.CustomPrefs.Remove(key);
 0213                        dbContext.ItemDisplayPreferences.Add(libraryDisplayPreferences);
 214                    }
 215
 0216                    foreach (var (key, value) in dto.CustomPrefs)
 217                    {
 218                        // Custom display preferences can have a key collision.
 0219                        var indexKey = $"{displayPreferences.UserId}|{itemId}|{displayPreferences.Client}|{key}";
 0220                        if (!customDisplayPrefs.Contains(indexKey))
 221                        {
 0222                            dbContext.Add(new CustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPre
 0223                            customDisplayPrefs.Add(indexKey);
 224                        }
 225                    }
 226
 0227                    dbContext.Add(displayPreferences);
 228                }
 229
 0230                dbContext.SaveChanges();
 231            }
 232
 233            try
 234            {
 0235                File.Move(dbFilePath, dbFilePath + ".old");
 236
 0237                var journalPath = dbFilePath + "-journal";
 0238                if (File.Exists(journalPath))
 239                {
 0240                    File.Move(journalPath, dbFilePath + ".old-journal");
 241                }
 0242            }
 0243            catch (IOException e)
 244            {
 0245                _logger.LogError(e, "Error renaming legacy display preferences database to 'displaypreferences.db.old'")
 0246            }
 0247        }
 248    }
 249}