< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MigrateDisplayPreferencesDb
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 119
Coverable lines: 119
Total lines: 230
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 50
Branch coverage: 0%
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%
get_Id()100%210%
get_Name()100%210%
get_PerformOnNewInstall()100%210%
Perform()0%2550500%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/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 Emby.Server.Implementations.Data;
 8using Jellyfin.Data.Entities;
 9using Jellyfin.Data.Enums;
 10using Jellyfin.Server.Implementations;
 11using MediaBrowser.Controller;
 12using MediaBrowser.Controller.Library;
 13using MediaBrowser.Model.Dto;
 14using Microsoft.Data.Sqlite;
 15using Microsoft.EntityFrameworkCore;
 16using Microsoft.Extensions.Logging;
 17
 18namespace Jellyfin.Server.Migrations.Routines
 19{
 20    /// <summary>
 21    /// The migration routine for migrating the display preferences database to EF Core.
 22    /// </summary>
 23    public class MigrateDisplayPreferencesDb : IMigrationRoutine
 24    {
 25        private const string DbFilename = "displaypreferences.db";
 26
 27        private readonly ILogger<MigrateDisplayPreferencesDb> _logger;
 28        private readonly IServerApplicationPaths _paths;
 29        private readonly IDbContextFactory<JellyfinDbContext> _provider;
 30        private readonly JsonSerializerOptions _jsonOptions;
 31        private readonly IUserManager _userManager;
 32
 33        /// <summary>
 34        /// Initializes a new instance of the <see cref="MigrateDisplayPreferencesDb"/> class.
 35        /// </summary>
 36        /// <param name="logger">The logger.</param>
 37        /// <param name="paths">The server application paths.</param>
 38        /// <param name="provider">The database provider.</param>
 39        /// <param name="userManager">The user manager.</param>
 40        public MigrateDisplayPreferencesDb(
 41            ILogger<MigrateDisplayPreferencesDb> logger,
 42            IServerApplicationPaths paths,
 43            IDbContextFactory<JellyfinDbContext> provider,
 44            IUserManager userManager)
 45        {
 046            _logger = logger;
 047            _paths = paths;
 048            _provider = provider;
 049            _userManager = userManager;
 050            _jsonOptions = new JsonSerializerOptions();
 051            _jsonOptions.Converters.Add(new JsonStringEnumConverter());
 052        }
 53
 54        /// <inheritdoc />
 055        public Guid Id => Guid.Parse("06387815-C3CC-421F-A888-FB5F9992BEA8");
 56
 57        /// <inheritdoc />
 058        public string Name => "MigrateDisplayPreferencesDatabase";
 59
 60        /// <inheritdoc />
 061        public bool PerformOnNewInstall => false;
 62
 63        /// <inheritdoc />
 64        public void Perform()
 65        {
 066            HomeSectionType[] defaults =
 067            {
 068                HomeSectionType.SmallLibraryTiles,
 069                HomeSectionType.Resume,
 070                HomeSectionType.ResumeAudio,
 071                HomeSectionType.LiveTv,
 072                HomeSectionType.NextUp,
 073                HomeSectionType.LatestMedia,
 074                HomeSectionType.None,
 075            };
 76
 077            var chromecastDict = new Dictionary<string, ChromecastVersion>(StringComparer.OrdinalIgnoreCase)
 078            {
 079                { "stable", ChromecastVersion.Stable },
 080                { "nightly", ChromecastVersion.Unstable },
 081                { "unstable", ChromecastVersion.Unstable }
 082            };
 83
 084            var displayPrefs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
 085            var customDisplayPrefs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
 086            var dbFilePath = Path.Combine(_paths.DataPath, DbFilename);
 087            using (var connection = new SqliteConnection($"Filename={dbFilePath}"))
 88            {
 089                connection.Open();
 090                using var dbContext = _provider.CreateDbContext();
 91
 092                var results = connection.Query("SELECT * FROM userdisplaypreferences");
 093                foreach (var result in results)
 94                {
 095                    var dto = JsonSerializer.Deserialize<DisplayPreferencesDto>(result.GetStream(3), _jsonOptions);
 096                    if (dto is null)
 97                    {
 98                        continue;
 99                    }
 100
 0101                    var itemId = result.GetGuid(1);
 0102                    var dtoUserId = itemId;
 0103                    var client = result.GetString(2);
 0104                    var displayPreferencesKey = $"{dtoUserId}|{itemId}|{client}";
 0105                    if (displayPrefs.Contains(displayPreferencesKey))
 106                    {
 107                        // Duplicate display preference.
 108                        continue;
 109                    }
 110
 0111                    displayPrefs.Add(displayPreferencesKey);
 0112                    var existingUser = _userManager.GetUserById(dtoUserId);
 0113                    if (existingUser is null)
 114                    {
 0115                        _logger.LogWarning("User with ID {UserId} does not exist in the database, skipping migration.", 
 0116                        continue;
 117                    }
 118
 0119                    var chromecastVersion = dto.CustomPrefs.TryGetValue("chromecastVersion", out var version)
 0120                                            && !string.IsNullOrEmpty(version)
 0121                        ? chromecastDict[version]
 0122                        : ChromecastVersion.Stable;
 0123                    dto.CustomPrefs.Remove("chromecastVersion");
 124
 0125                    var displayPreferences = new DisplayPreferences(dtoUserId, itemId, client)
 0126                    {
 0127                        IndexBy = Enum.TryParse<IndexingKind>(dto.IndexBy, true, out var indexBy) ? indexBy : null,
 0128                        ShowBackdrop = dto.ShowBackdrop,
 0129                        ShowSidebar = dto.ShowSidebar,
 0130                        ScrollDirection = dto.ScrollDirection,
 0131                        ChromecastVersion = chromecastVersion,
 0132                        SkipForwardLength = dto.CustomPrefs.TryGetValue("skipForwardLength", out var length) && int.TryP
 0133                            ? skipForwardLength
 0134                            : 30000,
 0135                        SkipBackwardLength = dto.CustomPrefs.TryGetValue("skipBackLength", out length) && int.TryParse(l
 0136                            ? skipBackwardLength
 0137                            : 10000,
 0138                        EnableNextVideoInfoOverlay = !dto.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var 
 0139                        DashboardTheme = dto.CustomPrefs.TryGetValue("dashboardtheme", out var theme) ? theme : string.E
 0140                        TvHome = dto.CustomPrefs.TryGetValue("tvhome", out var home) ? home : string.Empty
 0141                    };
 142
 0143                    dto.CustomPrefs.Remove("skipForwardLength");
 0144                    dto.CustomPrefs.Remove("skipBackLength");
 0145                    dto.CustomPrefs.Remove("enableNextVideoInfoOverlay");
 0146                    dto.CustomPrefs.Remove("dashboardtheme");
 0147                    dto.CustomPrefs.Remove("tvhome");
 148
 0149                    for (int i = 0; i < 7; i++)
 150                    {
 0151                        var key = "homesection" + i;
 0152                        dto.CustomPrefs.TryGetValue(key, out var homeSection);
 153
 0154                        displayPreferences.HomeSections.Add(new HomeSection
 0155                        {
 0156                            Order = i,
 0157                            Type = Enum.TryParse<HomeSectionType>(homeSection, true, out var type) ? type : defaults[i]
 0158                        });
 159
 0160                        dto.CustomPrefs.Remove(key);
 161                    }
 162
 0163                    var defaultLibraryPrefs = new ItemDisplayPreferences(displayPreferences.UserId, Guid.Empty, displayP
 0164                    {
 0165                        SortBy = dto.SortBy ?? "SortName",
 0166                        SortOrder = dto.SortOrder,
 0167                        RememberIndexing = dto.RememberIndexing,
 0168                        RememberSorting = dto.RememberSorting,
 0169                    };
 170
 0171                    dbContext.Add(defaultLibraryPrefs);
 172
 0173                    foreach (var key in dto.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.Or
 174                    {
 0175                        if (!Guid.TryParse(key.AsSpan().Slice("landing-".Length), out var landingItemId))
 176                        {
 177                            continue;
 178                        }
 179
 0180                        var libraryDisplayPreferences = new ItemDisplayPreferences(displayPreferences.UserId, landingIte
 0181                        {
 0182                            SortBy = dto.SortBy ?? "SortName",
 0183                            SortOrder = dto.SortOrder,
 0184                            RememberIndexing = dto.RememberIndexing,
 0185                            RememberSorting = dto.RememberSorting,
 0186                        };
 187
 0188                        if (Enum.TryParse<ViewType>(dto.ViewType, true, out var viewType))
 189                        {
 0190                            libraryDisplayPreferences.ViewType = viewType;
 191                        }
 192
 0193                        dto.CustomPrefs.Remove(key);
 0194                        dbContext.ItemDisplayPreferences.Add(libraryDisplayPreferences);
 195                    }
 196
 0197                    foreach (var (key, value) in dto.CustomPrefs)
 198                    {
 199                        // Custom display preferences can have a key collision.
 0200                        var indexKey = $"{displayPreferences.UserId}|{itemId}|{displayPreferences.Client}|{key}";
 0201                        if (!customDisplayPrefs.Contains(indexKey))
 202                        {
 0203                            dbContext.Add(new CustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPre
 0204                            customDisplayPrefs.Add(indexKey);
 205                        }
 206                    }
 207
 0208                    dbContext.Add(displayPreferences);
 209                }
 210
 0211                dbContext.SaveChanges();
 212            }
 213
 214            try
 215            {
 0216                File.Move(dbFilePath, dbFilePath + ".old");
 217
 0218                var journalPath = dbFilePath + "-journal";
 0219                if (File.Exists(journalPath))
 220                {
 0221                    File.Move(journalPath, dbFilePath + ".old-journal");
 222                }
 0223            }
 0224            catch (IOException e)
 225            {
 0226                _logger.LogError(e, "Error renaming legacy display preferences database to 'displaypreferences.db.old'")
 0227            }
 0228        }
 229    }
 230}