MigrateDisplayPreferencesDb.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 defaultDisplayPrefsId = "usersettings".GetMD5();
  76. var dbFilePath = Path.Combine(_paths.DataPath, DbFilename);
  77. using (var connection = SQLite3.Open(dbFilePath, ConnectionFlags.ReadOnly, null))
  78. {
  79. using var dbContext = _provider.CreateContext();
  80. var results = connection.Query("SELECT * FROM userdisplaypreferences");
  81. foreach (var result in results)
  82. {
  83. var dto = JsonSerializer.Deserialize<DisplayPreferencesDto>(result[3].ToString(), _jsonOptions);
  84. if (dto == null)
  85. {
  86. continue;
  87. }
  88. var itemId = new Guid(result[1].ToBlob());
  89. if (itemId == defaultDisplayPrefsId)
  90. {
  91. itemId = Guid.Empty;
  92. }
  93. var dtoUserId = new Guid(result[1].ToBlob());
  94. var existingUser = _userManager.GetUserById(dtoUserId);
  95. if (existingUser == null)
  96. {
  97. _logger.LogWarning("User with ID {UserId} does not exist in the database, skipping migration.", dtoUserId);
  98. continue;
  99. }
  100. var chromecastVersion = dto.CustomPrefs.TryGetValue("chromecastVersion", out var version)
  101. ? chromecastDict[version]
  102. : ChromecastVersion.Stable;
  103. dto.CustomPrefs.Remove("chromecastVersion");
  104. var displayPreferences = new DisplayPreferences(dtoUserId, itemId, result[2].ToString())
  105. {
  106. IndexBy = Enum.TryParse<IndexingKind>(dto.IndexBy, true, out var indexBy) ? indexBy : (IndexingKind?)null,
  107. ShowBackdrop = dto.ShowBackdrop,
  108. ShowSidebar = dto.ShowSidebar,
  109. ScrollDirection = dto.ScrollDirection,
  110. ChromecastVersion = chromecastVersion,
  111. SkipForwardLength = dto.CustomPrefs.TryGetValue("skipForwardLength", out var length)
  112. ? int.Parse(length, CultureInfo.InvariantCulture)
  113. : 30000,
  114. SkipBackwardLength = dto.CustomPrefs.TryGetValue("skipBackLength", out length)
  115. ? int.Parse(length, CultureInfo.InvariantCulture)
  116. : 10000,
  117. EnableNextVideoInfoOverlay = dto.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enabled)
  118. ? bool.Parse(enabled)
  119. : true,
  120. DashboardTheme = dto.CustomPrefs.TryGetValue("dashboardtheme", out var theme) ? theme : string.Empty,
  121. TvHome = dto.CustomPrefs.TryGetValue("tvhome", out var home) ? home : string.Empty
  122. };
  123. dto.CustomPrefs.Remove("skipForwardLength");
  124. dto.CustomPrefs.Remove("skipBackLength");
  125. dto.CustomPrefs.Remove("enableNextVideoInfoOverlay");
  126. dto.CustomPrefs.Remove("dashboardtheme");
  127. dto.CustomPrefs.Remove("tvhome");
  128. for (int i = 0; i < 7; i++)
  129. {
  130. var key = "homesection" + i;
  131. dto.CustomPrefs.TryGetValue(key, out var homeSection);
  132. displayPreferences.HomeSections.Add(new HomeSection
  133. {
  134. Order = i,
  135. Type = Enum.TryParse<HomeSectionType>(homeSection, true, out var type) ? type : defaults[i]
  136. });
  137. dto.CustomPrefs.Remove(key);
  138. }
  139. var defaultLibraryPrefs = new ItemDisplayPreferences(displayPreferences.UserId, Guid.Empty, displayPreferences.Client)
  140. {
  141. SortBy = dto.SortBy ?? "SortName",
  142. SortOrder = dto.SortOrder,
  143. RememberIndexing = dto.RememberIndexing,
  144. RememberSorting = dto.RememberSorting,
  145. };
  146. dbContext.Add(defaultLibraryPrefs);
  147. foreach (var key in dto.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.Ordinal)))
  148. {
  149. if (!Guid.TryParse(key.AsSpan().Slice("landing-".Length), out var landingItemId))
  150. {
  151. continue;
  152. }
  153. var libraryDisplayPreferences = new ItemDisplayPreferences(displayPreferences.UserId, landingItemId, displayPreferences.Client)
  154. {
  155. SortBy = dto.SortBy ?? "SortName",
  156. SortOrder = dto.SortOrder,
  157. RememberIndexing = dto.RememberIndexing,
  158. RememberSorting = dto.RememberSorting,
  159. };
  160. if (Enum.TryParse<ViewType>(dto.ViewType, true, out var viewType))
  161. {
  162. libraryDisplayPreferences.ViewType = viewType;
  163. }
  164. dto.CustomPrefs.Remove(key);
  165. dbContext.ItemDisplayPreferences.Add(libraryDisplayPreferences);
  166. }
  167. foreach (var (key, value) in dto.CustomPrefs)
  168. {
  169. dbContext.Add(new CustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client, key, value));
  170. }
  171. dbContext.Add(displayPreferences);
  172. }
  173. dbContext.SaveChanges();
  174. }
  175. try
  176. {
  177. File.Move(dbFilePath, dbFilePath + ".old");
  178. var journalPath = dbFilePath + "-journal";
  179. if (File.Exists(journalPath))
  180. {
  181. File.Move(journalPath, dbFilePath + ".old-journal");
  182. }
  183. }
  184. catch (IOException e)
  185. {
  186. _logger.LogError(e, "Error renaming legacy display preferences database to 'displaypreferences.db.old'");
  187. }
  188. }
  189. }
  190. }