MigrateDisplayPreferencesDb.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.Json;
  7. using System.Text.Json.Serialization;
  8. using Jellyfin.Data.Entities;
  9. using Jellyfin.Data.Enums;
  10. using Jellyfin.Server.Implementations;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Model.Entities;
  14. using Microsoft.Extensions.Logging;
  15. using SQLitePCL.pretty;
  16. namespace Jellyfin.Server.Migrations.Routines
  17. {
  18. /// <summary>
  19. /// The migration routine for migrating the display preferences database to EF Core.
  20. /// </summary>
  21. public class MigrateDisplayPreferencesDb : IMigrationRoutine
  22. {
  23. private const string DbFilename = "displaypreferences.db";
  24. private readonly ILogger<MigrateDisplayPreferencesDb> _logger;
  25. private readonly IServerApplicationPaths _paths;
  26. private readonly JellyfinDbProvider _provider;
  27. private readonly JsonSerializerOptions _jsonOptions;
  28. private readonly IUserManager _userManager;
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="MigrateDisplayPreferencesDb"/> class.
  31. /// </summary>
  32. /// <param name="logger">The logger.</param>
  33. /// <param name="paths">The server application paths.</param>
  34. /// <param name="provider">The database provider.</param>
  35. /// <param name="userManager">The user manager.</param>
  36. public MigrateDisplayPreferencesDb(
  37. ILogger<MigrateDisplayPreferencesDb> logger,
  38. IServerApplicationPaths paths,
  39. JellyfinDbProvider provider,
  40. IUserManager userManager)
  41. {
  42. _logger = logger;
  43. _paths = paths;
  44. _provider = provider;
  45. _userManager = userManager;
  46. _jsonOptions = new JsonSerializerOptions();
  47. _jsonOptions.Converters.Add(new JsonStringEnumConverter());
  48. }
  49. /// <inheritdoc />
  50. public Guid Id => Guid.Parse("06387815-C3CC-421F-A888-FB5F9992BEA8");
  51. /// <inheritdoc />
  52. public string Name => "MigrateDisplayPreferencesDatabase";
  53. /// <inheritdoc />
  54. public bool PerformOnNewInstall => false;
  55. /// <inheritdoc />
  56. public void Perform()
  57. {
  58. HomeSectionType[] defaults =
  59. {
  60. HomeSectionType.SmallLibraryTiles,
  61. HomeSectionType.Resume,
  62. HomeSectionType.ResumeAudio,
  63. HomeSectionType.LiveTv,
  64. HomeSectionType.NextUp,
  65. HomeSectionType.LatestMedia,
  66. HomeSectionType.None,
  67. };
  68. var chromecastDict = new Dictionary<string, ChromecastVersion>(StringComparer.OrdinalIgnoreCase)
  69. {
  70. { "stable", ChromecastVersion.Stable },
  71. { "nightly", ChromecastVersion.Unstable },
  72. { "unstable", ChromecastVersion.Unstable }
  73. };
  74. var dbFilePath = Path.Combine(_paths.DataPath, DbFilename);
  75. using (var connection = SQLite3.Open(dbFilePath, ConnectionFlags.ReadOnly, null))
  76. {
  77. using var dbContext = _provider.CreateContext();
  78. var results = connection.Query("SELECT * FROM userdisplaypreferences");
  79. foreach (var result in results)
  80. {
  81. var dto = JsonSerializer.Deserialize<DisplayPreferencesDto>(result[3].ToString(), _jsonOptions);
  82. if (dto == null)
  83. {
  84. continue;
  85. }
  86. var dtoUserId = new Guid(result[1].ToBlob());
  87. var existingUser = _userManager.GetUserById(dtoUserId);
  88. if (existingUser == null)
  89. {
  90. _logger.LogWarning("User with ID {UserId} does not exist in the database, skipping migration.", dtoUserId);
  91. continue;
  92. }
  93. var chromecastVersion = dto.CustomPrefs.TryGetValue("chromecastVersion", out var version)
  94. ? chromecastDict[version]
  95. : ChromecastVersion.Stable;
  96. var displayPreferences = new DisplayPreferences(dtoUserId, result[2].ToString())
  97. {
  98. IndexBy = Enum.TryParse<IndexingKind>(dto.IndexBy, true, out var indexBy) ? indexBy : (IndexingKind?)null,
  99. ShowBackdrop = dto.ShowBackdrop,
  100. ShowSidebar = dto.ShowSidebar,
  101. ScrollDirection = dto.ScrollDirection,
  102. ChromecastVersion = chromecastVersion,
  103. SkipForwardLength = dto.CustomPrefs.TryGetValue("skipForwardLength", out var length)
  104. ? int.Parse(length, CultureInfo.InvariantCulture)
  105. : 30000,
  106. SkipBackwardLength = dto.CustomPrefs.TryGetValue("skipBackLength", out length)
  107. ? int.Parse(length, CultureInfo.InvariantCulture)
  108. : 10000,
  109. EnableNextVideoInfoOverlay = dto.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enabled)
  110. ? bool.Parse(enabled)
  111. : true,
  112. DashboardTheme = dto.CustomPrefs.TryGetValue("dashboardtheme", out var theme) ? theme : string.Empty,
  113. TvHome = dto.CustomPrefs.TryGetValue("tvhome", out var home) ? home : string.Empty
  114. };
  115. for (int i = 0; i < 7; i++)
  116. {
  117. dto.CustomPrefs.TryGetValue("homesection" + i, out var homeSection);
  118. displayPreferences.HomeSections.Add(new HomeSection
  119. {
  120. Order = i,
  121. Type = Enum.TryParse<HomeSectionType>(homeSection, true, out var type) ? type : defaults[i]
  122. });
  123. }
  124. var defaultLibraryPrefs = new ItemDisplayPreferences(displayPreferences.UserId, Guid.Empty, displayPreferences.Client)
  125. {
  126. SortBy = dto.SortBy ?? "SortName",
  127. SortOrder = dto.SortOrder,
  128. RememberIndexing = dto.RememberIndexing,
  129. RememberSorting = dto.RememberSorting,
  130. };
  131. dbContext.Add(defaultLibraryPrefs);
  132. foreach (var key in dto.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.Ordinal)))
  133. {
  134. if (!Guid.TryParse(key.AsSpan().Slice("landing-".Length), out var itemId))
  135. {
  136. continue;
  137. }
  138. var libraryDisplayPreferences = new ItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client)
  139. {
  140. SortBy = dto.SortBy ?? "SortName",
  141. SortOrder = dto.SortOrder,
  142. RememberIndexing = dto.RememberIndexing,
  143. RememberSorting = dto.RememberSorting,
  144. };
  145. if (Enum.TryParse<ViewType>(dto.ViewType, true, out var viewType))
  146. {
  147. libraryDisplayPreferences.ViewType = viewType;
  148. }
  149. dbContext.ItemDisplayPreferences.Add(libraryDisplayPreferences);
  150. }
  151. dbContext.Add(displayPreferences);
  152. }
  153. dbContext.SaveChanges();
  154. }
  155. try
  156. {
  157. File.Move(dbFilePath, dbFilePath + ".old");
  158. var journalPath = dbFilePath + "-journal";
  159. if (File.Exists(journalPath))
  160. {
  161. File.Move(journalPath, dbFilePath + ".old-journal");
  162. }
  163. }
  164. catch (IOException e)
  165. {
  166. _logger.LogError(e, "Error renaming legacy display preferences database to 'displaypreferences.db.old'");
  167. }
  168. }
  169. }
  170. }