< 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: 67
Coverable lines: 67
Total lines: 153
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%
get_Id()100%210%
get_Name()100%210%
get_PerformOnNewInstall()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.Data.Entities;
 6using Jellyfin.Server.Implementations;
 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    public class MigrateActivityLogDb : IMigrationRoutine
 18    {
 19        private const string DbFilename = "activitylog.db";
 20
 21        private readonly ILogger<MigrateActivityLogDb> _logger;
 22        private readonly IDbContextFactory<JellyfinDbContext> _provider;
 23        private readonly IServerApplicationPaths _paths;
 24
 25        /// <summary>
 26        /// Initializes a new instance of the <see cref="MigrateActivityLogDb"/> class.
 27        /// </summary>
 28        /// <param name="logger">The logger.</param>
 29        /// <param name="paths">The server application paths.</param>
 30        /// <param name="provider">The database provider.</param>
 31        public MigrateActivityLogDb(ILogger<MigrateActivityLogDb> logger, IServerApplicationPaths paths, IDbContextFacto
 32        {
 033            _logger = logger;
 034            _provider = provider;
 035            _paths = paths;
 036        }
 37
 38        /// <inheritdoc/>
 039        public Guid Id => Guid.Parse("3793eb59-bc8c-456c-8b9f-bd5a62a42978");
 40
 41        /// <inheritdoc/>
 042        public string Name => "MigrateActivityLogDatabase";
 43
 44        /// <inheritdoc/>
 045        public bool PerformOnNewInstall => false;
 46
 47        /// <inheritdoc/>
 48        public void Perform()
 49        {
 050            var logLevelDictionary = new Dictionary<string, LogLevel>(StringComparer.OrdinalIgnoreCase)
 051            {
 052                { "None", LogLevel.None },
 053                { "Trace", LogLevel.Trace },
 054                { "Debug", LogLevel.Debug },
 055                { "Information", LogLevel.Information },
 056                { "Info", LogLevel.Information },
 057                { "Warn", LogLevel.Warning },
 058                { "Warning", LogLevel.Warning },
 059                { "Error", LogLevel.Error },
 060                { "Critical", LogLevel.Critical }
 061            };
 62
 063            var dataPath = _paths.DataPath;
 064            using (var connection = new SqliteConnection($"Filename={Path.Combine(dataPath, DbFilename)}"))
 65            {
 066                connection.Open();
 67
 068                using var userDbConnection = new SqliteConnection($"Filename={Path.Combine(dataPath, "users.db")}");
 069                userDbConnection.Open();
 070                _logger.LogWarning("Migrating the activity database may take a while, do not stop Jellyfin.");
 071                using var dbContext = _provider.CreateDbContext();
 72
 73                // Make sure that the database is empty in case of failed migration due to power outages, etc.
 074                dbContext.ActivityLogs.RemoveRange(dbContext.ActivityLogs);
 075                dbContext.SaveChanges();
 76                // Reset the autoincrement counter
 077                dbContext.Database.ExecuteSqlRaw("UPDATE sqlite_sequence SET seq = 0 WHERE name = 'ActivityLog';");
 078                dbContext.SaveChanges();
 79
 080                var newEntries = new List<ActivityLog>();
 81
 082                var queryResult = connection.Query("SELECT * FROM ActivityLog ORDER BY Id");
 83
 084                foreach (var entry in queryResult)
 85                {
 086                    if (!logLevelDictionary.TryGetValue(entry.GetString(8), out var severity))
 87                    {
 088                        severity = LogLevel.Trace;
 89                    }
 90
 091                    var guid = Guid.Empty;
 092                    if (!entry.IsDBNull(6) && !entry.TryGetGuid(6, out guid))
 93                    {
 094                        var id = entry.GetString(6);
 95                        // This is not a valid Guid, see if it is an internal ID from an old Emby schema
 096                        _logger.LogWarning("Invalid Guid in UserId column: {Guid}", id);
 97
 098                        using var statement = userDbConnection.PrepareStatement("SELECT guid FROM LocalUsersv2 WHERE Id=
 099                        statement.TryBind("@Id", id);
 100
 0101                        using var reader = statement.ExecuteReader();
 0102                        if (reader.HasRows && reader.Read() && reader.TryGetGuid(0, out guid))
 103                        {
 104                            // Successfully parsed a Guid from the user table.
 0105                            break;
 106                        }
 107                    }
 108
 0109                    var newEntry = new ActivityLog(entry.GetString(1), entry.GetString(4), guid)
 0110                    {
 0111                        DateCreated = entry.GetDateTime(7),
 0112                        LogSeverity = severity
 0113                    };
 114
 0115                    if (entry.TryGetString(2, out var result))
 116                    {
 0117                        newEntry.Overview = result;
 118                    }
 119
 0120                    if (entry.TryGetString(3, out result))
 121                    {
 0122                        newEntry.ShortOverview = result;
 123                    }
 124
 0125                    if (entry.TryGetString(5, out result))
 126                    {
 0127                        newEntry.ItemId = result;
 128                    }
 129
 0130                    newEntries.Add(newEntry);
 131                }
 132
 0133                dbContext.ActivityLogs.AddRange(newEntries);
 0134                dbContext.SaveChanges();
 135            }
 136
 137            try
 138            {
 0139                File.Move(Path.Combine(dataPath, DbFilename), Path.Combine(dataPath, DbFilename + ".old"));
 140
 0141                var journalPath = Path.Combine(dataPath, DbFilename + "-journal");
 0142                if (File.Exists(journalPath))
 143                {
 0144                    File.Move(journalPath, Path.Combine(dataPath, DbFilename + ".old-journal"));
 145                }
 0146            }
 0147            catch (IOException e)
 148            {
 0149                _logger.LogError(e, "Error renaming legacy activity log database to 'activitylog.db.old'");
 0150            }
 0151        }
 152    }
 153}