MigrateLibraryUserData.cs 5.2 KB

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