MigrateDisplayPreferencesDb.cs 10 KB

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