< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MigrateActivityLogDb
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 64
Coverable lines: 64
Total lines: 147
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 22
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
Perform()0%506220%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/MigrateActivityLogDb.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using Emby.Server.Implementations.Data;
 5using Jellyfin.Database.Implementations;
 6using Jellyfin.Database.Implementations.Entities;
 7using MediaBrowser.Controller;
 8using Microsoft.Data.Sqlite;
 9using Microsoft.EntityFrameworkCore;
 10using Microsoft.Extensions.Logging;
 11
 12namespace Jellyfin.Server.Migrations.Routines
 13{
 14    /// <summary>
 15    /// The migration routine for migrating the activity log database to EF Core.
 16    /// </summary>
 17#pragma warning disable CS0618 // Type or member is obsolete
 18    [JellyfinMigration("2025-04-20T07:00:00", nameof(MigrateActivityLogDb), "3793eb59-bc8c-456c-8b9f-bd5a62a42978")]
 19    public class MigrateActivityLogDb : IMigrationRoutine
 20#pragma warning restore CS0618 // Type or member is obsolete
 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 void Perform()
 43        {
 044            var logLevelDictionary = new Dictionary<string, LogLevel>(StringComparer.OrdinalIgnoreCase)
 045            {
 046                { "None", LogLevel.None },
 047                { "Trace", LogLevel.Trace },
 048                { "Debug", LogLevel.Debug },
 049                { "Information", LogLevel.Information },
 050                { "Info", LogLevel.Information },
 051                { "Warn", LogLevel.Warning },
 052                { "Warning", LogLevel.Warning },
 053                { "Error", LogLevel.Error },
 054                { "Critical", LogLevel.Critical }
 055            };
 56
 057            var dataPath = _paths.DataPath;
 058            using (var connection = new SqliteConnection($"Filename={Path.Combine(dataPath, DbFilename)}"))
 59            {
 060                connection.Open();
 61
 062                using var userDbConnection = new SqliteConnection($"Filename={Path.Combine(dataPath, "users.db")}");
 063                userDbConnection.Open();
 064                _logger.LogWarning("Migrating the activity database may take a while, do not stop Jellyfin.");
 065                using var dbContext = _provider.CreateDbContext();
 66
 67                // Make sure that the database is empty in case of failed migration due to power outages, etc.
 068                dbContext.ActivityLogs.RemoveRange(dbContext.ActivityLogs);
 069                dbContext.SaveChanges();
 70                // Reset the autoincrement counter
 071                dbContext.Database.ExecuteSqlRaw("UPDATE sqlite_sequence SET seq = 0 WHERE name = 'ActivityLog';");
 072                dbContext.SaveChanges();
 73
 074                var newEntries = new List<ActivityLog>();
 75
 076                var queryResult = connection.Query("SELECT * FROM ActivityLog ORDER BY Id");
 77
 078                foreach (var entry in queryResult)
 79                {
 080                    if (!logLevelDictionary.TryGetValue(entry.GetString(8), out var severity))
 81                    {
 082                        severity = LogLevel.Trace;
 83                    }
 84
 085                    var guid = Guid.Empty;
 086                    if (!entry.IsDBNull(6) && !entry.TryGetGuid(6, out guid))
 87                    {
 088                        var id = entry.GetString(6);
 89                        // This is not a valid Guid, see if it is an internal ID from an old Emby schema
 090                        _logger.LogWarning("Invalid Guid in UserId column: {Guid}", id);
 91
 092                        using var statement = userDbConnection.PrepareStatement("SELECT guid FROM LocalUsersv2 WHERE Id=
 093                        statement.TryBind("@Id", id);
 94
 095                        using var reader = statement.ExecuteReader();
 096                        if (reader.HasRows && reader.Read() && reader.TryGetGuid(0, out guid))
 97                        {
 98                            // Successfully parsed a Guid from the user table.
 099                            break;
 100                        }
 101                    }
 102
 0103                    var newEntry = new ActivityLog(entry.GetString(1), entry.GetString(4), guid)
 0104                    {
 0105                        DateCreated = entry.GetDateTime(7),
 0106                        LogSeverity = severity
 0107                    };
 108
 0109                    if (entry.TryGetString(2, out var result))
 110                    {
 0111                        newEntry.Overview = result;
 112                    }
 113
 0114                    if (entry.TryGetString(3, out result))
 115                    {
 0116                        newEntry.ShortOverview = result;
 117                    }
 118
 0119                    if (entry.TryGetString(5, out result))
 120                    {
 0121                        newEntry.ItemId = result;
 122                    }
 123
 0124                    newEntries.Add(newEntry);
 125                }
 126
 0127                dbContext.ActivityLogs.AddRange(newEntries);
 0128                dbContext.SaveChanges();
 129            }
 130
 131            try
 132            {
 0133                File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
 134
 0135                var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
 0136                if (File.Exists(journalPath))
 137                {
 0138                    File.Move(journalPath, Path.Combine(dataPath, DbFilename + ".old-journal"));
 139                }
 0140            }
 0141            catch (IOException e)
 142            {
 0143                _logger.LogError(e, "Error renaming legacy activity log database to 'activitylog.db.old'");
 0144            }
 0145        }
 146    }
 147}