MigrateUserDb.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. using System;
  2. using System.IO;
  3. using Emby.Server.Implementations.Data;
  4. using Emby.Server.Implementations.Serialization;
  5. using Jellyfin.Data.Entities;
  6. using Jellyfin.Data.Enums;
  7. using Jellyfin.Server.Implementations;
  8. using Jellyfin.Server.Implementations.Users;
  9. using MediaBrowser.Controller;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Model.Configuration;
  12. using MediaBrowser.Model.Users;
  13. using Microsoft.Extensions.Logging;
  14. using SQLitePCL.pretty;
  15. using JsonSerializer = System.Text.Json.JsonSerializer;
  16. namespace Jellyfin.Server.Migrations.Routines
  17. {
  18. /// <summary>
  19. /// The migration routine for migrating the user database to EF Core.
  20. /// </summary>
  21. public class MigrateUserDb : IMigrationRoutine
  22. {
  23. private const string DbFilename = "users.db";
  24. private readonly ILogger<MigrateUserDb> _logger;
  25. private readonly IServerApplicationPaths _paths;
  26. private readonly JellyfinDbProvider _provider;
  27. private readonly MyXmlSerializer _xmlSerializer;
  28. /// <summary>
  29. /// Initializes a new instance of the <see cref="MigrateUserDb"/> 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="xmlSerializer">The xml serializer.</param>
  35. public MigrateUserDb(
  36. ILogger<MigrateUserDb> logger,
  37. IServerApplicationPaths paths,
  38. JellyfinDbProvider provider,
  39. MyXmlSerializer xmlSerializer)
  40. {
  41. _logger = logger;
  42. _paths = paths;
  43. _provider = provider;
  44. _xmlSerializer = xmlSerializer;
  45. }
  46. /// <inheritdoc/>
  47. public Guid Id => Guid.Parse("5C4B82A2-F053-4009-BD05-B6FCAD82F14C");
  48. /// <inheritdoc/>
  49. public string Name => "MigrateUserDatabase";
  50. /// <inheritdoc/>
  51. public void Perform()
  52. {
  53. var dataPath = _paths.DataPath;
  54. _logger.LogInformation("Migrating the user database may take a while, do not stop Jellyfin.");
  55. using (var connection = SQLite3.Open(Path.Combine(dataPath, DbFilename), ConnectionFlags.ReadOnly, null))
  56. {
  57. var dbContext = _provider.CreateContext();
  58. var queryResult = connection.Query("SELECT * FROM LocalUsersv2");
  59. dbContext.RemoveRange(dbContext.Users);
  60. dbContext.SaveChanges();
  61. foreach (var entry in queryResult)
  62. {
  63. UserMockup mockup = JsonSerializer.Deserialize<UserMockup>(entry[2].ToBlob());
  64. var userDataDir = Path.Combine(_paths.UserConfigurationDirectoryPath, mockup.Name);
  65. var config = File.Exists(Path.Combine(userDataDir, "config.xml"))
  66. ? (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), Path.Combine(userDataDir, "config.xml"))
  67. : new UserConfiguration();
  68. var policy = File.Exists(Path.Combine(userDataDir, "policy.xml"))
  69. ? (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), Path.Combine(userDataDir, "policy.xml"))
  70. : new UserPolicy();
  71. policy.AuthenticationProviderId = policy.AuthenticationProviderId?.Replace(
  72. "Emby.Server.Implementations.Library",
  73. "Jellyfin.Server.Implementations.Users",
  74. StringComparison.Ordinal)
  75. ?? typeof(DefaultAuthenticationProvider).FullName;
  76. policy.PasswordResetProviderId = typeof(DefaultPasswordResetProvider).FullName;
  77. var user = new User(mockup.Name, policy.AuthenticationProviderId, string.Empty)
  78. {
  79. Id = entry[1].ReadGuidFromBlob(),
  80. InternalId = entry[0].ToInt64(),
  81. MaxParentalAgeRating = policy.MaxParentalRating,
  82. EnableUserPreferenceAccess = policy.EnableUserPreferenceAccess,
  83. RemoteClientBitrateLimit = policy.RemoteClientBitrateLimit,
  84. PasswordResetProviderId = policy.PasswordResetProviderId,
  85. InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount,
  86. LoginAttemptsBeforeLockout = policy.LoginAttemptsBeforeLockout == -1 ? null : new int?(policy.LoginAttemptsBeforeLockout),
  87. SubtitleMode = config.SubtitleMode,
  88. HidePlayedInLatest = config.HidePlayedInLatest,
  89. EnableLocalPassword = config.EnableLocalPassword,
  90. PlayDefaultAudioTrack = config.PlayDefaultAudioTrack,
  91. DisplayCollectionsView = config.DisplayCollectionsView,
  92. DisplayMissingEpisodes = config.DisplayMissingEpisodes,
  93. AudioLanguagePreference = config.AudioLanguagePreference,
  94. RememberAudioSelections = config.RememberAudioSelections,
  95. EnableNextEpisodeAutoPlay = config.EnableNextEpisodeAutoPlay,
  96. RememberSubtitleSelections = config.RememberSubtitleSelections,
  97. SubtitleLanguagePreference = config.SubtitleLanguagePreference,
  98. Password = mockup.Password,
  99. EasyPassword = mockup.EasyPassword,
  100. LastLoginDate = mockup.LastLoginDate ?? DateTime.MinValue,
  101. LastActivityDate = mockup.LastActivityDate ?? DateTime.MinValue
  102. };
  103. if (mockup.ImageInfos.Length > 0)
  104. {
  105. ItemImageInfo info = mockup.ImageInfos[0];
  106. user.ProfileImage = new ImageInfo(info.Path, info.Width, info.Height)
  107. {
  108. LastModified = info.DateModified
  109. };
  110. }
  111. user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
  112. user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
  113. user.SetPermission(PermissionKind.IsDisabled, policy.IsDisabled);
  114. user.SetPermission(PermissionKind.EnableSharedDeviceControl, policy.EnableSharedDeviceControl);
  115. user.SetPermission(PermissionKind.EnableRemoteAccess, policy.EnableRemoteAccess);
  116. user.SetPermission(PermissionKind.EnableLiveTvManagement, policy.EnableLiveTvManagement);
  117. user.SetPermission(PermissionKind.EnableLiveTvAccess, policy.EnableLiveTvAccess);
  118. user.SetPermission(PermissionKind.EnableMediaPlayback, policy.EnableMediaPlayback);
  119. user.SetPermission(PermissionKind.EnableAudioPlaybackTranscoding, policy.EnableAudioPlaybackTranscoding);
  120. user.SetPermission(PermissionKind.EnableVideoPlaybackTranscoding, policy.EnableVideoPlaybackTranscoding);
  121. user.SetPermission(PermissionKind.EnableContentDeletion, policy.EnableContentDeletion);
  122. user.SetPermission(PermissionKind.EnableContentDownloading, policy.EnableContentDownloading);
  123. user.SetPermission(PermissionKind.EnableSyncTranscoding, policy.EnableSyncTranscoding);
  124. user.SetPermission(PermissionKind.EnableMediaConversion, policy.EnableMediaConversion);
  125. user.SetPermission(PermissionKind.EnableAllChannels, policy.EnableAllChannels);
  126. user.SetPermission(PermissionKind.EnableAllDevices, policy.EnableAllDevices);
  127. user.SetPermission(PermissionKind.EnableAllFolders, policy.EnableAllFolders);
  128. user.SetPermission(PermissionKind.EnableRemoteControlOfOtherUsers, policy.EnableRemoteControlOfOtherUsers);
  129. user.SetPermission(PermissionKind.EnablePlaybackRemuxing, policy.EnablePlaybackRemuxing);
  130. user.SetPermission(PermissionKind.ForceRemoteSourceTranscoding, policy.ForceRemoteSourceTranscoding);
  131. user.SetPermission(PermissionKind.EnablePublicSharing, policy.EnablePublicSharing);
  132. foreach (var policyAccessSchedule in policy.AccessSchedules)
  133. {
  134. user.AccessSchedules.Add(policyAccessSchedule);
  135. }
  136. user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags);
  137. user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels);
  138. user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices);
  139. user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders);
  140. user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
  141. user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews);
  142. user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders);
  143. user.SetPreference(PreferenceKind.MyMediaExcludes, config.MyMediaExcludes);
  144. user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
  145. dbContext.Users.Add(user);
  146. }
  147. dbContext.SaveChanges();
  148. }
  149. try
  150. {
  151. File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
  152. var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
  153. if (File.Exists(journalPath))
  154. {
  155. File.Move(journalPath, Path.Combine(dataPath, DbFilename + ".old-journal"));
  156. }
  157. }
  158. catch (IOException e)
  159. {
  160. _logger.LogError(e, "Error renaming legacy user database to 'users.db.old'");
  161. }
  162. }
  163. #nullable disable
  164. internal class UserMockup
  165. {
  166. public string Password { get; set; }
  167. public string EasyPassword { get; set; }
  168. public DateTime? LastLoginDate { get; set; }
  169. public DateTime? LastActivityDate { get; set; }
  170. public string Name { get; set; }
  171. public ItemImageInfo[] ImageInfos { get; set; }
  172. }
  173. }
  174. }