< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MigrateActivityLogDb
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20250420070000_MigrateActivityLogDb.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 75
Coverable lines: 75
Total lines: 170
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 28
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/73) Branch coverage: 0% (0/28) Total lines: 16311/13/2026 - 12:19:51 AM Line coverage: 0% (0/75) Branch coverage: 0% (0/28) Total lines: 170 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/73) Branch coverage: 0% (0/28) Total lines: 16311/13/2026 - 12:19:51 AM Line coverage: 0% (0/75) Branch coverage: 0% (0/28) Total lines: 170

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
PerformAsync(...)100%210%
PerformCore()0%812280%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20250420070000_MigrateActivityLogDb.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.Threading;
 5using System.Threading.Tasks;
 6using Emby.Server.Implementations.Data;
 7using Jellyfin.Database.Implementations;
 8using Jellyfin.Database.Implementations.Entities;
 9using MediaBrowser.Controller;
 10using Microsoft.Data.Sqlite;
 11using Microsoft.EntityFrameworkCore;
 12using Microsoft.Extensions.Logging;
 13
 14namespace Jellyfin.Server.Migrations.Routines
 15{
 16    /// <summary>
 17    /// The migration routine for migrating the activity log database to EF Core.
 18    /// </summary>
 19    [JellyfinMigration("2025-04-20T07:00:00", nameof(MigrateActivityLogDb), "3793eb59-bc8c-456c-8b9f-bd5a62a42978")]
 20    public class MigrateActivityLogDb : IAsyncMigrationRoutine
 21    {
 22        private const string DbFilename = "activitylog.db";
 23
 24        private readonly ILogger<MigrateActivityLogDb> _logger;
 25        private readonly IDbContextFactory<JellyfinDbContext> _provider;
 26        private readonly IServerApplicationPaths _paths;
 27
 28        /// <summary>
 29        /// Initializes a new instance of the <see cref="MigrateActivityLogDb"/> 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        public MigrateActivityLogDb(ILogger<MigrateActivityLogDb> logger, IServerApplicationPaths paths, IDbContextFacto
 35        {
 036            _logger = logger;
 037            _provider = provider;
 038            _paths = paths;
 039        }
 40
 41        /// <inheritdoc />
 42        public Task PerformAsync(CancellationToken cancellationToken)
 43        {
 44            // This routine predates the async interface and has not been ported to async database access yet.
 045            PerformCore();
 046            return Task.CompletedTask;
 47        }
 48
 49        private void PerformCore()
 50        {
 051            var logLevelDictionary = new Dictionary<string, LogLevel>(StringComparer.OrdinalIgnoreCase)
 052            {
 053                { "None", LogLevel.None },
 054                { "Trace", LogLevel.Trace },
 055                { "Debug", LogLevel.Debug },
 056                { "Information", LogLevel.Information },
 057                { "Info", LogLevel.Information },
 058                { "Warn", LogLevel.Warning },
 059                { "Warning", LogLevel.Warning },
 060                { "Error", LogLevel.Error },
 061                { "Critical", LogLevel.Critical }
 062            };
 63
 064            var dataPath = _paths.DataPath;
 065            var activityLogPath = Path.Combine(dataPath, DbFilename);
 066            if (!File.Exists(activityLogPath))
 67            {
 068                _logger.LogWarning("{ActivityLogDb} doesn't exist, nothing to migrate", activityLogPath);
 069                return;
 70            }
 71
 072            using (var connection = new SqliteConnection($"Filename={activityLogPath}"))
 73            {
 074                connection.Open();
 075                var tableQuery = connection.Query("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='Activ
 076                foreach (var row in tableQuery)
 77                {
 078                    if (row.GetInt32(0) == 0)
 79                    {
 080                        _logger.LogWarning("Table 'ActivityLog' doesn't exist in {ActivityLogPath}, nothing to migrate",
 081                        return;
 82                    }
 83                }
 84
 085                using var userDbConnection = new SqliteConnection($"Filename={Path.Combine(dataPath, "users.db")}");
 086                userDbConnection.Open();
 087                _logger.LogWarning("Migrating the activity database may take a while, do not stop Jellyfin.");
 088                using var dbContext = _provider.CreateDbContext();
 89
 90                // Make sure that the database is empty in case of failed migration due to power outages, etc.
 091                dbContext.ActivityLogs.RemoveRange(dbContext.ActivityLogs);
 092                dbContext.SaveChanges();
 93                // Reset the autoincrement counter
 094                dbContext.Database.ExecuteSqlRaw("UPDATE sqlite_sequence SET seq = 0 WHERE name = 'ActivityLog';");
 095                dbContext.SaveChanges();
 96
 097                var newEntries = new List<ActivityLog>();
 98
 099                var queryResult = connection.Query("SELECT * FROM ActivityLog ORDER BY Id");
 100
 0101                foreach (var entry in queryResult)
 102                {
 0103                    if (!logLevelDictionary.TryGetValue(entry.GetString(8), out var severity))
 104                    {
 0105                        severity = LogLevel.Trace;
 106                    }
 107
 0108                    var guid = Guid.Empty;
 0109                    if (!entry.IsDBNull(6) && !entry.TryGetGuid(6, out guid))
 110                    {
 0111                        var id = entry.GetString(6);
 112                        // This is not a valid Guid, see if it is an internal ID from an old Emby schema
 0113                        _logger.LogWarning("Invalid Guid in UserId column: {Guid}", id);
 114
 0115                        using var statement = userDbConnection.PrepareStatement("SELECT guid FROM LocalUsersv2 WHERE Id=
 0116                        statement.TryBind("@Id", id);
 117
 0118                        using var reader = statement.ExecuteReader();
 0119                        if (reader.HasRows && reader.Read() && reader.TryGetGuid(0, out guid))
 120                        {
 121                            // Successfully parsed a Guid from the user table.
 0122                            break;
 123                        }
 124                    }
 125
 0126                    var newEntry = new ActivityLog(entry.GetString(1), entry.GetString(4), guid)
 0127                    {
 0128                        DateCreated = entry.GetDateTime(7),
 0129                        LogSeverity = severity
 0130                    };
 131
 0132                    if (entry.TryGetString(2, out var result))
 133                    {
 0134                        newEntry.Overview = result;
 135                    }
 136
 0137                    if (entry.TryGetString(3, out result))
 138                    {
 0139                        newEntry.ShortOverview = result;
 140                    }
 141
 0142                    if (entry.TryGetString(5, out result))
 143                    {
 0144                        newEntry.ItemId = result;
 145                    }
 146
 0147                    newEntries.Add(newEntry);
 148                }
 149
 0150                dbContext.ActivityLogs.AddRange(newEntries);
 0151                dbContext.SaveChanges();
 152            }
 153
 154            try
 155            {
 0156                File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
 157
 0158                var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
 0159                if (File.Exists(journalPath))
 160                {
 0161                    File.Move(journalPath, Path.Combine(dataPath, DbFilename + ".old-journal"));
 162                }
 0163            }
 0164            catch (IOException e)
 165            {
 0166                _logger.LogError(e, "Error renaming legacy activity log database to 'activitylog.db.old'");
 0167            }
 0168        }
 169    }
 170}