MigrateDisplayPreferencesDb.cs 9.0 KB

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