MigrateDisplayPreferencesDb.cs 10 KB

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