MigrateActivityLogDb.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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.Server.Implementations;
  7. using MediaBrowser.Controller;
  8. using Microsoft.EntityFrameworkCore;
  9. using Microsoft.Extensions.Logging;
  10. using SQLitePCL.pretty;
  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 JellyfinDbProvider _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, JellyfinDbProvider 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 void Perform()
  40. {
  41. var logLevelDictionary = new Dictionary<string, LogLevel>(StringComparer.OrdinalIgnoreCase)
  42. {
  43. { "None", LogLevel.None },
  44. { "Trace", LogLevel.Trace },
  45. { "Debug", LogLevel.Debug },
  46. { "Information", LogLevel.Information },
  47. { "Info", LogLevel.Information },
  48. { "Warn", LogLevel.Warning },
  49. { "Warning", LogLevel.Warning },
  50. { "Error", LogLevel.Error },
  51. { "Critical", LogLevel.Critical }
  52. };
  53. var dataPath = _paths.DataPath;
  54. using (var connection = SQLite3.Open(
  55. Path.Combine(dataPath, DbFilename),
  56. ConnectionFlags.ReadOnly,
  57. null))
  58. {
  59. using var userDbConnection = SQLite3.Open(Path.Combine(dataPath, "users.db"), ConnectionFlags.ReadOnly, null);
  60. _logger.LogWarning("Migrating the activity database may take a while, do not stop Jellyfin.");
  61. using var dbContext = _provider.CreateContext();
  62. var queryResult = connection.Query("SELECT * FROM ActivityLog ORDER BY Id");
  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. foreach (var entry in queryResult)
  71. {
  72. if (!logLevelDictionary.TryGetValue(entry[8].ToString(), out var severity))
  73. {
  74. severity = LogLevel.Trace;
  75. }
  76. var guid = Guid.Empty;
  77. if (entry[6].SQLiteType != SQLiteType.Null && !Guid.TryParse(entry[6].ToString(), out guid))
  78. {
  79. // This is not a valid Guid, see if it is an internal ID from an old Emby schema
  80. _logger.LogWarning("Invalid Guid in UserId column: ", entry[6].ToString());
  81. using var statement = userDbConnection.PrepareStatement("SELECT guid FROM LocalUsersv2 WHERE Id=@Id");
  82. statement.TryBind("@Id", entry[6].ToString());
  83. foreach (var row in statement.Query())
  84. {
  85. if (row.Count > 0 && Guid.TryParse(row[0].ToString(), out guid))
  86. {
  87. // Successfully parsed a Guid from the user table.
  88. break;
  89. }
  90. }
  91. }
  92. var newEntry = new ActivityLog(entry[1].ToString(), entry[4].ToString(), guid)
  93. {
  94. DateCreated = entry[7].ReadDateTime(),
  95. LogSeverity = severity
  96. };
  97. if (entry[2].SQLiteType != SQLiteType.Null)
  98. {
  99. newEntry.Overview = entry[2].ToString();
  100. }
  101. if (entry[3].SQLiteType != SQLiteType.Null)
  102. {
  103. newEntry.ShortOverview = entry[3].ToString();
  104. }
  105. if (entry[5].SQLiteType != SQLiteType.Null)
  106. {
  107. newEntry.ItemId = entry[5].ToString();
  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. }