< Summary - Jellyfin

Information
Class: Jellyfin.Server.Implementations.FullSystemBackup.BackupService
Assembly: Jellyfin.Server.Implementations
File(s): /srv/git/jellyfin/Jellyfin.Server.Implementations/FullSystemBackup/BackupService.cs
Line coverage
3%
Covered lines: 9
Uncovered lines: 261
Coverable lines: 270
Total lines: 590
Line coverage: 3.3%
Branch coverage
0%
Covered branches: 0
Total branches: 72
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 3/26/2026 - 12:14:14 AM Line coverage: 16.6% (8/48) Branch coverage: 0% (0/2) Total lines: 5603/31/2026 - 12:14:24 AM Line coverage: 16.6% (8/48) Branch coverage: 0% (0/2) Total lines: 5774/19/2026 - 12:14:27 AM Line coverage: 3% (8/266) Branch coverage: 0% (0/70) Total lines: 5776/28/2026 - 12:15:35 AM Line coverage: 3.3% (9/270) Branch coverage: 0% (0/72) Total lines: 590 3/26/2026 - 12:14:14 AM Line coverage: 16.6% (8/48) Branch coverage: 0% (0/2) Total lines: 5603/31/2026 - 12:14:24 AM Line coverage: 16.6% (8/48) Branch coverage: 0% (0/2) Total lines: 5774/19/2026 - 12:14:27 AM Line coverage: 3% (8/266) Branch coverage: 0% (0/70) Total lines: 5776/28/2026 - 12:15:35 AM Line coverage: 3.3% (9/270) Branch coverage: 0% (0/72) Total lines: 590

Coverage delta

Coverage delta 14 -14

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
.ctor(...)100%11100%
ScheduleRestoreAndRestartServer(...)100%210%
RestoreBackupAsync()0%702260%
TestBackupVersionCompatibility(...)0%620%
CreateBackupAsync()0%1056320%
GetBackupManifest()0%2040%
EnumerateBackups()0%4260%
GetManifest()0%620%
Map(...)100%210%
Map(...)100%210%
Map(...)100%210%
NormalizePathSeparator(...)100%210%

File(s)

/srv/git/jellyfin/Jellyfin.Server.Implementations/FullSystemBackup/BackupService.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.IO.Compression;
 5using System.Linq;
 6using System.Text.Json;
 7using System.Text.Json.Nodes;
 8using System.Text.Json.Serialization;
 9using System.Threading;
 10using System.Threading.Tasks;
 11using Jellyfin.Database.Implementations;
 12using Jellyfin.Server.Implementations.StorageHelpers;
 13using Jellyfin.Server.Implementations.SystemBackupService;
 14using MediaBrowser.Controller;
 15using MediaBrowser.Controller.Library;
 16using MediaBrowser.Controller.SystemBackupService;
 17using Microsoft.EntityFrameworkCore;
 18using Microsoft.EntityFrameworkCore.Infrastructure;
 19using Microsoft.EntityFrameworkCore.Migrations;
 20using Microsoft.Extensions.Hosting;
 21using Microsoft.Extensions.Logging;
 22
 23namespace Jellyfin.Server.Implementations.FullSystemBackup;
 24
 25/// <summary>
 26/// Contains methods for creating and restoring backups.
 27/// </summary>
 28public class BackupService : IBackupService
 29{
 30    private const string ManifestEntryName = "manifest.json";
 31    private readonly ILogger<BackupService> _logger;
 32    private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
 33    private readonly IServerApplicationHost _applicationHost;
 34    private readonly IServerApplicationPaths _applicationPaths;
 35    private readonly IJellyfinDatabaseProvider _jellyfinDatabaseProvider;
 36    private readonly IHostApplicationLifetime _hostApplicationLifetime;
 37    private readonly ILibraryManager _libraryManager;
 038    private static readonly JsonSerializerOptions _serializerSettings = new JsonSerializerOptions(JsonSerializerDefaults
 039    {
 040        AllowTrailingCommas = true,
 041        ReferenceHandler = ReferenceHandler.IgnoreCycles,
 042    };
 43
 2244    private readonly Version _backupEngineVersion = new Version(0, 2, 0);
 45
 46    /// <summary>
 47    /// Initializes a new instance of the <see cref="BackupService"/> class.
 48    /// </summary>
 49    /// <param name="logger">A logger.</param>
 50    /// <param name="dbProvider">A Database Factory.</param>
 51    /// <param name="applicationHost">The Application host.</param>
 52    /// <param name="applicationPaths">The application paths.</param>
 53    /// <param name="jellyfinDatabaseProvider">The Jellyfin database Provider in use.</param>
 54    /// <param name="applicationLifetime">The SystemManager.</param>
 55    /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
 56    public BackupService(
 57        ILogger<BackupService> logger,
 58        IDbContextFactory<JellyfinDbContext> dbProvider,
 59        IServerApplicationHost applicationHost,
 60        IServerApplicationPaths applicationPaths,
 61        IJellyfinDatabaseProvider jellyfinDatabaseProvider,
 62        IHostApplicationLifetime applicationLifetime,
 63        ILibraryManager libraryManager)
 64    {
 2265        _logger = logger;
 2266        _dbProvider = dbProvider;
 2267        _applicationHost = applicationHost;
 2268        _applicationPaths = applicationPaths;
 2269        _jellyfinDatabaseProvider = jellyfinDatabaseProvider;
 2270        _hostApplicationLifetime = applicationLifetime;
 2271        _libraryManager = libraryManager;
 2272    }
 73
 74    /// <inheritdoc/>
 75    public void ScheduleRestoreAndRestartServer(string archivePath)
 76    {
 077        _applicationHost.RestoreBackupPath = archivePath;
 078        _applicationHost.ShouldRestart = true;
 079        _applicationHost.NotifyPendingRestart();
 080        _ = Task.Run(async () =>
 081        {
 082            await Task.Delay(500).ConfigureAwait(false);
 083            _hostApplicationLifetime.StopApplication();
 084        });
 085    }
 86
 87    /// <inheritdoc/>
 88    public async Task RestoreBackupAsync(string archivePath)
 89    {
 090        _logger.LogWarning("Begin restoring system to {BackupArchive}", archivePath); // Info isn't cutting it
 091        if (!File.Exists(archivePath))
 92        {
 093            throw new FileNotFoundException($"Requested backup file '{archivePath}' does not exist.");
 94        }
 95
 096        StorageHelper.TestCommonPathsForStorageCapacity(_applicationPaths, _logger);
 97
 098        var fileStream = File.OpenRead(archivePath);
 099        await using (fileStream.ConfigureAwait(false))
 100        {
 0101            using var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Read, false);
 0102            var zipArchiveEntry = zipArchive.GetEntry(ManifestEntryName);
 103
 0104            if (zipArchiveEntry is null)
 105            {
 0106                throw new NotSupportedException($"The loaded archive '{archivePath}' does not appear to be a Jellyfin ba
 107            }
 108
 109            BackupManifest? manifest;
 0110            var manifestStream = await zipArchiveEntry.OpenAsync().ConfigureAwait(false);
 0111            await using (manifestStream.ConfigureAwait(false))
 112            {
 0113                manifest = await JsonSerializer.DeserializeAsync<BackupManifest>(manifestStream, _serializerSettings).Co
 114            }
 115
 0116            if (manifest!.ServerVersion > _applicationHost.ApplicationVersion) // newer versions of Jellyfin should be a
 117            {
 0118                throw new NotSupportedException($"The loaded archive '{archivePath}' is made for a newer version of Jell
 119            }
 120
 0121            if (!TestBackupVersionCompatibility(manifest.BackupEngineVersion))
 122            {
 0123                throw new NotSupportedException($"The loaded archive '{archivePath}' is made for a newer version of Jell
 124            }
 125
 126            void CopyDirectory(string source, string target, string[]? exclude = null)
 127            {
 128                var fullSourcePath = NormalizePathSeparator(Path.GetFullPath(source) + Path.DirectorySeparatorChar);
 129                var fullTargetRoot = Path.GetFullPath(target) + Path.DirectorySeparatorChar;
 130                var excludePaths = exclude?.Select(e => $"{source}/{e}/").ToArray();
 131                foreach (var item in zipArchive.Entries)
 132                {
 133                    var sourcePath = NormalizePathSeparator(Path.GetFullPath(item.FullName));
 134                    var targetPath = Path.GetFullPath(Path.Combine(target, Path.GetRelativePath(source, item.FullName)))
 135
 136                    if (excludePaths is not null && excludePaths.Any(e => item.FullName.StartsWith(e, StringComparison.O
 137                    {
 138                        continue;
 139                    }
 140
 141                    if (!sourcePath.StartsWith(fullSourcePath, StringComparison.Ordinal)
 142                        || !targetPath.StartsWith(fullTargetRoot, StringComparison.Ordinal)
 143                        || Path.EndsInDirectorySeparator(item.FullName))
 144                    {
 145                        continue;
 146                    }
 147
 148                    _logger.LogInformation("Restore and override {File}", targetPath);
 149
 150                    Directory.CreateDirectory(Path.GetDirectoryName(targetPath)!);
 151                    item.ExtractToFile(targetPath, overwrite: true);
 152                }
 153            }
 154
 0155            CopyDirectory("Config", _applicationPaths.ConfigurationDirectoryPath);
 0156            CopyDirectory("Data", _applicationPaths.DataPath, exclude: ["metadata", "metadata-default"]);
 0157            CopyDirectory("Root", _applicationPaths.RootFolderPath);
 0158            CopyDirectory("Data/metadata", _applicationPaths.InternalMetadataPath);
 0159            CopyDirectory("Data/metadata-default", _applicationPaths.DefaultInternalMetadataPath);
 160
 0161            if (manifest.Options.Database)
 162            {
 0163                _logger.LogInformation("Begin restoring Database");
 0164                var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
 0165                await using (dbContext.ConfigureAwait(false))
 166                {
 167                    // restore migration history manually
 0168                    var historyEntry = zipArchive.GetEntry(NormalizePathSeparator(Path.Combine("Database", $"{nameof(His
 0169                    if (historyEntry is null)
 170                    {
 0171                        _logger.LogInformation("No backup of the history table in archive. This is required for Jellyfin
 0172                        throw new InvalidOperationException("Cannot restore backup that has no History data.");
 173                    }
 174
 175                    HistoryRow[] historyEntries;
 0176                    var historyArchive = await historyEntry.OpenAsync().ConfigureAwait(false);
 0177                    await using (historyArchive.ConfigureAwait(false))
 178                    {
 0179                        historyEntries = await JsonSerializer.DeserializeAsync<HistoryRow[]>(historyArchive).ConfigureAw
 0180                            throw new InvalidOperationException("Cannot restore backup that has no History data.");
 181                    }
 182
 0183                    var historyRepository = dbContext.GetService<IHistoryRepository>();
 0184                    await historyRepository.CreateIfNotExistsAsync().ConfigureAwait(false);
 185
 0186                    foreach (var item in await historyRepository.GetAppliedMigrationsAsync(CancellationToken.None).Confi
 187                    {
 0188                        var insertScript = historyRepository.GetDeleteScript(item.MigrationId);
 0189                        await dbContext.Database.ExecuteSqlRawAsync(insertScript).ConfigureAwait(false);
 190                    }
 191
 0192                    foreach (var item in historyEntries)
 193                    {
 0194                        var insertScript = historyRepository.GetInsertScript(item);
 0195                        await dbContext.Database.ExecuteSqlRawAsync(insertScript).ConfigureAwait(false);
 196                    }
 197
 0198                    dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
 0199                    var entityTypes = typeof(JellyfinDbContext).GetProperties(System.Reflection.BindingFlags.Public | Sy
 0200                        .Where(e => e.PropertyType.IsAssignableTo(typeof(IQueryable)))
 0201                        .Select(e => (Type: e, Set: e.GetValue(dbContext) as IQueryable))
 0202                        .ToArray();
 203
 0204                    var tableNames = entityTypes.Select(f => dbContext.Model.FindEntityType(f.Type.PropertyType.GetGener
 0205                    _logger.LogInformation("Begin purging database");
 0206                    await _jellyfinDatabaseProvider.PurgeDatabase(dbContext, tableNames).ConfigureAwait(false);
 0207                    _logger.LogInformation("Database Purged");
 208
 0209                    foreach (var entityType in entityTypes)
 210                    {
 0211                        _logger.LogInformation("Read backup of {Table}", entityType.Type.Name);
 212
 0213                        var zipEntry = zipArchive.GetEntry(NormalizePathSeparator(Path.Combine("Database", $"{entityType
 0214                        if (zipEntry is null)
 215                        {
 0216                            _logger.LogInformation("No backup of expected table {Table} is present in backup, continuing
 0217                            continue;
 218                        }
 219
 0220                        var zipEntryStream = await zipEntry.OpenAsync().ConfigureAwait(false);
 0221                        await using (zipEntryStream.ConfigureAwait(false))
 222                        {
 0223                            _logger.LogInformation("Restore backup of {Table}", entityType.Type.Name);
 0224                            var records = 0;
 0225                            await foreach (var item in JsonSerializer.DeserializeAsyncEnumerable<JsonObject>(zipEntryStr
 226                            {
 0227                                var entity = item.Deserialize(entityType.Type.PropertyType.GetGenericArguments()[0]);
 0228                                if (entity is null)
 229                                {
 0230                                    throw new InvalidOperationException($"Cannot deserialize entity '{item}'");
 231                                }
 232
 233                                try
 234                                {
 0235                                    records++;
 0236                                    dbContext.Add(entity);
 0237                                }
 0238                                catch (Exception ex)
 239                                {
 0240                                    _logger.LogError(ex, "Could not store entity {Entity}, continuing anyway", item);
 0241                                }
 242                            }
 243
 0244                            _logger.LogInformation("Prepared to restore {Number} entries for {Table}", records, entityTy
 245                        }
 0246                    }
 247
 0248                    _logger.LogInformation("Try restore Database");
 0249                    await dbContext.SaveChangesAsync().ConfigureAwait(false);
 0250                    _logger.LogInformation("Restored database");
 0251                }
 0252            }
 253
 0254            _logger.LogInformation("Restored Jellyfin system from {Date}", manifest.DateCreated);
 0255        }
 0256    }
 257
 258    private bool TestBackupVersionCompatibility(Version backupEngineVersion)
 259    {
 0260        if (backupEngineVersion == _backupEngineVersion)
 261        {
 0262            return true;
 263        }
 264
 0265        return false;
 266    }
 267
 268    /// <inheritdoc/>
 269    public async Task<BackupManifestDto> CreateBackupAsync(BackupOptionsDto backupOptions)
 270    {
 271        // Creating a backup runs a database optimization and reads the entire database under a transaction, both of
 272        // which heavily contend with an active library scan and could capture an inconsistent database state.
 0273        if (_libraryManager.IsScanRunning)
 274        {
 0275            _logger.LogWarning("Cannot create a backup while a library scan is running.");
 0276            throw new InvalidOperationException("Cannot create a backup while a library scan is running. Please try agai
 277        }
 278
 0279        var manifest = new BackupManifest()
 0280        {
 0281            DateCreated = DateTime.UtcNow,
 0282            ServerVersion = _applicationHost.ApplicationVersion,
 0283            DatabaseTables = null!,
 0284            BackupEngineVersion = _backupEngineVersion,
 0285            Options = Map(backupOptions)
 0286        };
 287
 0288        _logger.LogInformation("Running database optimization before backup");
 289
 0290        await _jellyfinDatabaseProvider.RunScheduledOptimisation(CancellationToken.None).ConfigureAwait(false);
 291
 0292        var backupFolder = Path.Combine(_applicationPaths.BackupPath);
 293
 0294        if (!Directory.Exists(backupFolder))
 295        {
 0296            Directory.CreateDirectory(backupFolder);
 297        }
 298
 0299        var backupStorageSpace = StorageHelper.GetFreeSpaceOf(_applicationPaths.BackupPath);
 300
 301        const long FiveGigabyte = 5_368_709_115;
 0302        if (backupStorageSpace.FreeSpace < FiveGigabyte)
 303        {
 0304            throw new InvalidOperationException($"The backup directory '{backupStorageSpace.Path}' does not have at leas
 305        }
 306
 0307        var backupPath = Path.Combine(backupFolder, $"jellyfin-backup-{manifest.DateCreated.ToLocalTime():yyyyMMddHHmmss
 308
 309        try
 310        {
 0311            _logger.LogInformation("Attempting to create a new backup at {BackupPath}", backupPath);
 0312            var fileStream = File.OpenWrite(backupPath);
 0313            await using (fileStream.ConfigureAwait(false))
 0314            using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create, false))
 315            {
 0316                _logger.LogInformation("Starting backup process");
 0317                var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
 0318                await using (dbContext.ConfigureAwait(false))
 319                {
 0320                    dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
 321
 322                    static IAsyncEnumerable<object> GetValues(IQueryable dbSet)
 323                    {
 324                        var method = dbSet.GetType().GetMethod(nameof(DbSet<object>.AsAsyncEnumerable))!;
 325                        var enumerable = method.Invoke(dbSet, null)!;
 326                        return (IAsyncEnumerable<object>)enumerable;
 327                    }
 328
 329                    // include the migration history as well
 0330                    var historyRepository = dbContext.GetService<IHistoryRepository>();
 0331                    var migrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false);
 332
 0333                    ICollection<(Type Type, string SourceName, Func<IAsyncEnumerable<object>> ValueFactory)> entityTypes
 0334                    [
 0335                        .. typeof(JellyfinDbContext)
 0336                            .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instan
 0337                            .Where(e => e.PropertyType.IsAssignableTo(typeof(IQueryable)))
 0338                            .Select(e => (Type: e.PropertyType, dbContext.Model.FindEntityType(e.PropertyType.GetGeneric
 0339                        (Type: typeof(HistoryRow), SourceName: nameof(HistoryRow), ValueFactory: () => migrations.ToAsyn
 0340                    ];
 0341                    manifest.DatabaseTables = entityTypes.Select(e => e.Type.Name).ToArray();
 0342                    var transaction = await dbContext.Database.BeginTransactionAsync().ConfigureAwait(false);
 343
 0344                    await using (transaction.ConfigureAwait(false))
 345                    {
 0346                        _logger.LogInformation("Begin Database backup");
 347
 0348                        foreach (var entityType in entityTypes)
 349                        {
 0350                            _logger.LogInformation("Begin backup of entity {Table}", entityType.SourceName);
 0351                            var zipEntry = zipArchive.CreateEntry(NormalizePathSeparator(Path.Combine("Database", $"{ent
 0352                            var entities = 0;
 0353                            var zipEntryStream = await zipEntry.OpenAsync().ConfigureAwait(false);
 0354                            await using (zipEntryStream.ConfigureAwait(false))
 355                            {
 0356                                var jsonSerializer = new Utf8JsonWriter(zipEntryStream);
 0357                                await using (jsonSerializer.ConfigureAwait(false))
 358                                {
 0359                                    jsonSerializer.WriteStartArray();
 360
 0361                                    var set = entityType.ValueFactory().ConfigureAwait(false);
 0362                                    await foreach (var item in set.ConfigureAwait(false))
 363                                    {
 0364                                        entities++;
 365                                        try
 366                                        {
 0367                                            using var document = JsonSerializer.SerializeToDocument(item, _serializerSet
 0368                                            document.WriteTo(jsonSerializer);
 0369                                        }
 0370                                        catch (Exception ex)
 371                                        {
 0372                                            _logger.LogError(ex, "Could not load entity {Entity}", item);
 0373                                            throw;
 374                                        }
 375                                    }
 376
 0377                                    jsonSerializer.WriteEndArray();
 378                                }
 0379                            }
 380
 0381                            _logger.LogInformation("Backup of entity {Table} with {Number} created", entityType.SourceNa
 0382                        }
 383                    }
 0384                }
 385
 0386                _logger.LogInformation("Backup of folder {Table}", _applicationPaths.ConfigurationDirectoryPath);
 0387                foreach (var item in Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.xml", Sea
 0388                             .Union(Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.json", Sea
 389                {
 0390                    await zipArchive.CreateEntryFromFileAsync(item, NormalizePathSeparator(Path.Combine("Config", Path.G
 391                }
 392
 393                void CopyDirectory(string source, string target, string filter = "*")
 394                {
 395                    if (!Directory.Exists(source))
 396                    {
 397                        return;
 398                    }
 399
 400                    _logger.LogInformation("Backup of folder {Table}", source);
 401
 402                    foreach (var item in Directory.EnumerateFiles(source, filter, SearchOption.AllDirectories))
 403                    {
 404                        // TODO: @bond make async
 405                        zipArchive.CreateEntryFromFile(item, NormalizePathSeparator(Path.Combine(target, Path.GetRelativ
 406                    }
 407                }
 408
 0409                CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "users"), Path.Combine("Config"
 0410                CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks"), Path.Combine
 0411                CopyDirectory(Path.Combine(_applicationPaths.RootFolderPath), "Root");
 0412                CopyDirectory(Path.Combine(_applicationPaths.DataPath, "collections"), Path.Combine("Data", "collections
 0413                CopyDirectory(Path.Combine(_applicationPaths.DataPath, "playlists"), Path.Combine("Data", "playlists"));
 0414                CopyDirectory(Path.Combine(_applicationPaths.DataPath, "ScheduledTasks"), Path.Combine("Data", "Schedule
 0415                if (backupOptions.Subtitles)
 416                {
 0417                    CopyDirectory(Path.Combine(_applicationPaths.DataPath, "subtitles"), Path.Combine("Data", "subtitles
 418                }
 419
 0420                if (backupOptions.Trickplay)
 421                {
 0422                    CopyDirectory(Path.Combine(_applicationPaths.DataPath, "trickplay"), Path.Combine("Data", "trickplay
 423                }
 424
 0425                if (backupOptions.Metadata)
 426                {
 0427                    CopyDirectory(Path.Combine(_applicationPaths.InternalMetadataPath), Path.Combine("Data", "metadata")
 428
 429                    // If a custom metadata path is configured, the default location may still contain data.
 0430                    if (!string.Equals(
 0431                            Path.GetFullPath(_applicationPaths.DefaultInternalMetadataPath),
 0432                            Path.GetFullPath(_applicationPaths.InternalMetadataPath),
 0433                            StringComparison.OrdinalIgnoreCase))
 434                    {
 0435                        CopyDirectory(Path.Combine(_applicationPaths.DefaultInternalMetadataPath), Path.Combine("Data", 
 436                    }
 437                }
 438
 0439                var manifestStream = await zipArchive.CreateEntry(ManifestEntryName).OpenAsync().ConfigureAwait(false);
 0440                await using (manifestStream.ConfigureAwait(false))
 441                {
 0442                    await JsonSerializer.SerializeAsync(manifestStream, manifest).ConfigureAwait(false);
 443                }
 0444            }
 445
 0446            _logger.LogInformation("Backup created");
 0447            return Map(manifest, backupPath);
 448        }
 0449        catch (Exception ex)
 450        {
 0451            _logger.LogError(ex, "Failed to create backup, removing {BackupPath}", backupPath);
 452            try
 453            {
 0454                if (File.Exists(backupPath))
 455                {
 0456                    File.Delete(backupPath);
 457                }
 0458            }
 0459            catch (Exception innerEx)
 460            {
 0461                _logger.LogWarning(innerEx, "Unable to remove failed backup");
 0462            }
 463
 0464            throw;
 465        }
 0466    }
 467
 468    /// <inheritdoc/>
 469    public async Task<BackupManifestDto?> GetBackupManifest(string archivePath)
 470    {
 0471        if (!File.Exists(archivePath))
 472        {
 0473            return null;
 474        }
 475
 476        BackupManifest? manifest;
 477        try
 478        {
 0479            manifest = await GetManifest(archivePath).ConfigureAwait(false);
 0480        }
 0481        catch (Exception ex)
 482        {
 0483            _logger.LogWarning(ex, "Tried to load manifest from archive {Path} but failed", archivePath);
 0484            return null;
 485        }
 486
 0487        if (manifest is null)
 488        {
 0489            return null;
 490        }
 491
 0492        return Map(manifest, archivePath);
 0493    }
 494
 495    /// <inheritdoc/>
 496    public async Task<BackupManifestDto[]> EnumerateBackups()
 497    {
 0498        if (!Directory.Exists(_applicationPaths.BackupPath))
 499        {
 0500            return [];
 501        }
 502
 0503        var archives = Directory.EnumerateFiles(_applicationPaths.BackupPath, "*.zip");
 0504        var manifests = new List<BackupManifestDto>();
 0505        foreach (var item in archives)
 506        {
 507            try
 508            {
 0509                var manifest = await GetManifest(item).ConfigureAwait(false);
 510
 0511                if (manifest is null)
 512                {
 0513                    continue;
 514                }
 515
 0516                manifests.Add(Map(manifest, item));
 0517            }
 0518            catch (Exception ex)
 519            {
 0520                _logger.LogWarning(ex, "Tried to load manifest from archive {Path} but failed", item);
 0521            }
 0522        }
 523
 0524        return manifests.ToArray();
 0525    }
 526
 527    private static async ValueTask<BackupManifest?> GetManifest(string archivePath)
 528    {
 0529        var archiveStream = File.OpenRead(archivePath);
 0530        await using (archiveStream.ConfigureAwait(false))
 531        {
 0532            using var zipStream = new ZipArchive(archiveStream, ZipArchiveMode.Read);
 0533            var manifestEntry = zipStream.GetEntry(ManifestEntryName);
 0534            if (manifestEntry is null)
 535            {
 0536                return null;
 537            }
 538
 0539            var manifestStream = await manifestEntry.OpenAsync().ConfigureAwait(false);
 0540            await using (manifestStream.ConfigureAwait(false))
 541            {
 0542                return await JsonSerializer.DeserializeAsync<BackupManifest>(manifestStream, _serializerSettings).Config
 543            }
 0544        }
 0545    }
 546
 547    private static BackupManifestDto Map(BackupManifest manifest, string path)
 548    {
 0549        return new BackupManifestDto()
 0550        {
 0551            BackupEngineVersion = manifest.BackupEngineVersion,
 0552            DateCreated = manifest.DateCreated,
 0553            ServerVersion = manifest.ServerVersion,
 0554            Path = path,
 0555            Options = Map(manifest.Options)
 0556        };
 557    }
 558
 559    private static BackupOptionsDto Map(BackupOptions options)
 560    {
 0561        return new BackupOptionsDto()
 0562        {
 0563            Metadata = options.Metadata,
 0564            Subtitles = options.Subtitles,
 0565            Trickplay = options.Trickplay,
 0566            Database = options.Database
 0567        };
 568    }
 569
 570    private static BackupOptions Map(BackupOptionsDto options)
 571    {
 0572        return new BackupOptions()
 0573        {
 0574            Metadata = options.Metadata,
 0575            Subtitles = options.Subtitles,
 0576            Trickplay = options.Trickplay,
 0577            Database = options.Database
 0578        };
 579    }
 580
 581    /// <summary>
 582    /// Windows is able to handle '/' as a path seperator in zip files
 583    /// but linux isn't able to handle '\' as a path seperator in zip files,
 584    /// So normalize to '/'.
 585    /// </summary>
 586    /// <param name="path">The path to normalize.</param>
 587    /// <returns>The normalized path. </returns>
 588    private static string NormalizePathSeparator(string path)
 0589        => path.Replace('\\', '/');
 590}