2
0

MigrateDisplayPreferencesDb.cs 9.5 KB

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