MigrateLibraryUserData.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #pragma warning disable RS0030 // Do not use banned APIs
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Emby.Server.Implementations.Data;
  9. using Jellyfin.Database.Implementations;
  10. using Jellyfin.Server.Implementations.Item;
  11. using Jellyfin.Server.ServerSetupApp;
  12. using MediaBrowser.Controller;
  13. using Microsoft.Data.Sqlite;
  14. using Microsoft.EntityFrameworkCore;
  15. using Microsoft.Extensions.Logging;
  16. namespace Jellyfin.Server.Migrations.Routines;
  17. [JellyfinMigration("2025-06-18T01:00:00", nameof(MigrateLibraryUserData))]
  18. [JellyfinMigrationBackup(JellyfinDb = true)]
  19. internal class MigrateLibraryUserData : IAsyncMigrationRoutine
  20. {
  21. private const string DbFilename = "library.db.old";
  22. private readonly IStartupLogger _logger;
  23. private readonly IServerApplicationPaths _paths;
  24. private readonly IDbContextFactory<JellyfinDbContext> _provider;
  25. public MigrateLibraryUserData(
  26. IStartupLogger<MigrateLibraryDb> startupLogger,
  27. IDbContextFactory<JellyfinDbContext> provider,
  28. IServerApplicationPaths paths)
  29. {
  30. _logger = startupLogger;
  31. _provider = provider;
  32. _paths = paths;
  33. }
  34. public async Task PerformAsync(CancellationToken cancellationToken)
  35. {
  36. _logger.LogInformation("Migrating the userdata from library.db.old may take a while, do not stop Jellyfin.");
  37. var dataPath = _paths.DataPath;
  38. var libraryDbPath = Path.Combine(dataPath, DbFilename);
  39. if (!File.Exists(libraryDbPath))
  40. {
  41. _logger.LogError("Cannot migrate userdata from {LibraryDb} as it does not exist. This migration expects the MigrateLibraryDb to run first.", libraryDbPath);
  42. return;
  43. }
  44. var dbContext = await _provider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
  45. await using (dbContext.ConfigureAwait(false))
  46. {
  47. if (!await dbContext.BaseItems.AnyAsync(e => e.Id == BaseItemRepository.PlaceholderId, cancellationToken).ConfigureAwait(false))
  48. {
  49. // the placeholder baseitem has been deleted by the librarydb migration so we need to readd it.
  50. await dbContext.BaseItems.AddAsync(
  51. new Database.Implementations.Entities.BaseItemEntity()
  52. {
  53. Id = BaseItemRepository.PlaceholderId,
  54. Type = "PLACEHOLDER",
  55. Name = "This is a placeholder item for UserData that has been detacted from its original item"
  56. },
  57. cancellationToken)
  58. .ConfigureAwait(false);
  59. await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
  60. }
  61. var users = dbContext.Users.AsNoTracking().ToArray();
  62. var userIdBlacklist = new HashSet<int>();
  63. using var connection = new SqliteConnection($"Filename={libraryDbPath};Mode=ReadOnly");
  64. var retentionDate = DateTime.UtcNow;
  65. var queryResult = connection.Query(
  66. """
  67. SELECT key, userId, rating, played, playCount, isFavorite, playbackPositionTicks, lastPlayedDate, AudioStreamIndex, SubtitleStreamIndex FROM UserDatas
  68. WHERE NOT EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.UserDataKey = UserDatas.key)
  69. """);
  70. foreach (var entity in queryResult)
  71. {
  72. var userData = MigrateLibraryDb.GetUserData(users, entity, userIdBlacklist, _logger);
  73. if (userData is null)
  74. {
  75. var userDataId = entity.GetString(0);
  76. var internalUserId = entity.GetInt32(1);
  77. if (!userIdBlacklist.Contains(internalUserId))
  78. {
  79. _logger.LogError("Was not able to migrate user data with key {0} because its id {InternalId} does not match any existing user.", userDataId, internalUserId);
  80. userIdBlacklist.Add(internalUserId);
  81. }
  82. continue;
  83. }
  84. userData.ItemId = BaseItemRepository.PlaceholderId;
  85. userData.RetentionDate = retentionDate;
  86. dbContext.UserData.Add(userData);
  87. }
  88. _logger.LogInformation("Try saving {NewSaved} UserData entries.", dbContext.UserData.Local.Count);
  89. await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
  90. }
  91. }
  92. }