MigrateActivityLogDb.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using Emby.Server.Implementations.Data;
  5. using Jellyfin.Data.Entities;
  6. using Jellyfin.Database.Implementations;
  7. using MediaBrowser.Controller;
  8. using Microsoft.Data.Sqlite;
  9. using Microsoft.EntityFrameworkCore;
  10. using Microsoft.Extensions.Logging;
  11. namespace Jellyfin.Server.Migrations.Routines
  12. {
  13. /// <summary>
  14. /// The migration routine for migrating the activity log database to EF Core.
  15. /// </summary>
  16. public class MigrateActivityLogDb : IMigrationRoutine
  17. {
  18. private const string DbFilename = "activitylog.db";
  19. private readonly ILogger<MigrateActivityLogDb> _logger;
  20. private readonly IDbContextFactory<JellyfinDbContext> _provider;
  21. private readonly IServerApplicationPaths _paths;
  22. /// <summary>
  23. /// Initializes a new instance of the <see cref="MigrateActivityLogDb"/> class.
  24. /// </summary>
  25. /// <param name="logger">The logger.</param>
  26. /// <param name="paths">The server application paths.</param>
  27. /// <param name="provider">The database provider.</param>
  28. public MigrateActivityLogDb(ILogger<MigrateActivityLogDb> logger, IServerApplicationPaths paths, IDbContextFactory<JellyfinDbContext> provider)
  29. {
  30. _logger = logger;
  31. _provider = provider;
  32. _paths = paths;
  33. }
  34. /// <inheritdoc/>
  35. public Guid Id => Guid.Parse("3793eb59-bc8c-456c-8b9f-bd5a62a42978");
  36. /// <inheritdoc/>
  37. public string Name => "MigrateActivityLogDatabase";
  38. /// <inheritdoc/>
  39. public bool PerformOnNewInstall => false;
  40. /// <inheritdoc/>
  41. public void Perform()
  42. {
  43. var logLevelDictionary = new Dictionary<string, LogLevel>(StringComparer.OrdinalIgnoreCase)
  44. {
  45. { "None", LogLevel.None },
  46. { "Trace", LogLevel.Trace },
  47. { "Debug", LogLevel.Debug },
  48. { "Information", LogLevel.Information },
  49. { "Info", LogLevel.Information },
  50. { "Warn", LogLevel.Warning },
  51. { "Warning", LogLevel.Warning },
  52. { "Error", LogLevel.Error },
  53. { "Critical", LogLevel.Critical }
  54. };
  55. var dataPath = _paths.DataPath;
  56. using (var connection = new SqliteConnection($"Filename={Path.Combine(dataPath, DbFilename)}"))
  57. {
  58. connection.Open();
  59. using var userDbConnection = new SqliteConnection($"Filename={Path.Combine(dataPath, "users.db")}");
  60. userDbConnection.Open();
  61. _logger.LogWarning("Migrating the activity database may take a while, do not stop Jellyfin.");
  62. using var dbContext = _provider.CreateDbContext();
  63. // Make sure that the database is empty in case of failed migration due to power outages, etc.
  64. dbContext.ActivityLogs.RemoveRange(dbContext.ActivityLogs);
  65. dbContext.SaveChanges();
  66. // Reset the autoincrement counter
  67. dbContext.Database.ExecuteSqlRaw("UPDATE sqlite_sequence SET seq = 0 WHERE name = 'ActivityLog';");
  68. dbContext.SaveChanges();
  69. var newEntries = new List<ActivityLog>();
  70. var queryResult = connection.Query("SELECT * FROM ActivityLog ORDER BY Id");
  71. foreach (var entry in queryResult)
  72. {
  73. if (!logLevelDictionary.TryGetValue(entry.GetString(8), out var severity))
  74. {
  75. severity = LogLevel.Trace;
  76. }
  77. var guid = Guid.Empty;
  78. if (!entry.IsDBNull(6) && !entry.TryGetGuid(6, out guid))
  79. {
  80. var id = entry.GetString(6);
  81. // This is not a valid Guid, see if it is an internal ID from an old Emby schema
  82. _logger.LogWarning("Invalid Guid in UserId column: {Guid}", id);
  83. using var statement = userDbConnection.PrepareStatement("SELECT guid FROM LocalUsersv2 WHERE Id=@Id");
  84. statement.TryBind("@Id", id);
  85. using var reader = statement.ExecuteReader();
  86. if (reader.HasRows && reader.Read() && reader.TryGetGuid(0, out guid))
  87. {
  88. // Successfully parsed a Guid from the user table.
  89. break;
  90. }
  91. }
  92. var newEntry = new ActivityLog(entry.GetString(1), entry.GetString(4), guid)
  93. {
  94. DateCreated = entry.GetDateTime(7),
  95. LogSeverity = severity
  96. };
  97. if (entry.TryGetString(2, out var result))
  98. {
  99. newEntry.Overview = result;
  100. }
  101. if (entry.TryGetString(3, out result))
  102. {
  103. newEntry.ShortOverview = result;
  104. }
  105. if (entry.TryGetString(5, out result))
  106. {
  107. newEntry.ItemId = result;
  108. }
  109. newEntries.Add(newEntry);
  110. }
  111. dbContext.ActivityLogs.AddRange(newEntries);
  112. dbContext.SaveChanges();
  113. }
  114. try
  115. {
  116. File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
  117. var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
  118. if (File.Exists(journalPath))
  119. {
  120. File.Move(journalPath, Path.Combine(dataPath, DbFilename + ".old-journal"));
  121. }
  122. }
  123. catch (IOException e)
  124. {
  125. _logger.LogError(e, "Error renaming legacy activity log database to 'activitylog.db.old'");
  126. }
  127. }
  128. }
  129. }