From 83b2c472378410a3d0e7e8065cb627d2520d99d4 Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Sat, 22 Feb 2025 10:23:33 +0100 Subject: Remove deprecated GetWakeOnLanInfo endpoint --- Jellyfin.Api/Controllers/SystemController.cs | 16 ---------------- 1 file changed, 16 deletions(-) (limited to 'Jellyfin.Api/Controllers/SystemController.cs') diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 6c5ce4715..0ee11c070 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -212,20 +212,4 @@ public class SystemController : BaseJellyfinApiController FileStream stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, fileShare, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous); return File(stream, "text/plain; charset=utf-8"); } - - /// - /// Gets wake on lan information. - /// - /// Information retrieved. - /// An with the WakeOnLan infos. - [HttpGet("WakeOnLanInfo")] - [Authorize] - [Obsolete("This endpoint is obsolete.")] - [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult> GetWakeOnLanInfo() - { - var result = _networkManager.GetMacAddresses() - .Select(i => new WakeOnLanInfo(i)); - return Ok(result); - } } -- cgit v1.2.3 From a0931baa8eb879898f4bc4049176ed3bdb4d80d1 Mon Sep 17 00:00:00 2001 From: JPVenson Date: Mon, 21 Apr 2025 05:06:50 +0300 Subject: Add Api and startup check for sufficient storage capacity (#13888) --- Emby.Server.Implementations/SystemManager.cs | 34 ++- Jellyfin.Api/Controllers/SystemController.cs | 14 ++ .../Models/SystemInfoDtos/FolderStorageDto.cs | 46 ++++ .../Models/SystemInfoDtos/LibraryStorageDto.cs | 37 +++ .../Models/SystemInfoDtos/SystemStorageDto.cs | 67 ++++++ .../StorageHelpers/StorageHelper.cs | 109 +++++++++ Jellyfin.Server/Program.cs | 4 + MediaBrowser.Controller/ISystemManager.cs | 7 + MediaBrowser.Model/System/FolderStorageInfo.cs | 32 +++ MediaBrowser.Model/System/LibraryStorageInfo.cs | 25 ++ MediaBrowser.Model/System/SystemInfo.cs | 254 +++++++++++---------- MediaBrowser.Model/System/SystemStorageInfo.cs | 56 +++++ 12 files changed, 560 insertions(+), 125 deletions(-) create mode 100644 Jellyfin.Api/Models/SystemInfoDtos/FolderStorageDto.cs create mode 100644 Jellyfin.Api/Models/SystemInfoDtos/LibraryStorageDto.cs create mode 100644 Jellyfin.Api/Models/SystemInfoDtos/SystemStorageDto.cs create mode 100644 Jellyfin.Server.Implementations/StorageHelpers/StorageHelper.cs create mode 100644 MediaBrowser.Model/System/FolderStorageInfo.cs create mode 100644 MediaBrowser.Model/System/LibraryStorageInfo.cs create mode 100644 MediaBrowser.Model/System/SystemStorageInfo.cs (limited to 'Jellyfin.Api/Controllers/SystemController.cs') diff --git a/Emby.Server.Implementations/SystemManager.cs b/Emby.Server.Implementations/SystemManager.cs index 5936df7f1..92b59b23c 100644 --- a/Emby.Server.Implementations/SystemManager.cs +++ b/Emby.Server.Implementations/SystemManager.cs @@ -1,9 +1,12 @@ +using System; using System.Linq; using System.Threading.Tasks; +using Jellyfin.Server.Implementations.StorageHelpers; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Updates; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Library; using MediaBrowser.Model.System; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; @@ -19,6 +22,7 @@ public class SystemManager : ISystemManager private readonly IServerConfigurationManager _configurationManager; private readonly IStartupOptions _startupOptions; private readonly IInstallationManager _installationManager; + private readonly ILibraryManager _libraryManager; /// /// Initializes a new instance of the class. @@ -29,13 +33,15 @@ public class SystemManager : ISystemManager /// Instance of . /// Instance of . /// Instance of . + /// Instance of . public SystemManager( IHostApplicationLifetime applicationLifetime, IServerApplicationHost applicationHost, IServerApplicationPaths applicationPaths, IServerConfigurationManager configurationManager, IStartupOptions startupOptions, - IInstallationManager installationManager) + IInstallationManager installationManager, + ILibraryManager libraryManager) { _applicationLifetime = applicationLifetime; _applicationHost = applicationHost; @@ -43,6 +49,7 @@ public class SystemManager : ISystemManager _configurationManager = configurationManager; _startupOptions = startupOptions; _installationManager = installationManager; + _libraryManager = libraryManager; } /// @@ -57,6 +64,7 @@ public class SystemManager : ISystemManager WebSocketPortNumber = _applicationHost.HttpPort, CompletedInstallations = _installationManager.CompletedInstallations.ToArray(), Id = _applicationHost.SystemId, +#pragma warning disable CS0618 // Type or member is obsolete ProgramDataPath = _applicationPaths.ProgramDataPath, WebPath = _applicationPaths.WebPath, LogPath = _applicationPaths.LogDirectoryPath, @@ -64,6 +72,7 @@ public class SystemManager : ISystemManager InternalMetadataPath = _applicationPaths.InternalMetadataPath, CachePath = _applicationPaths.CachePath, TranscodingTempPath = _configurationManager.GetTranscodePath(), +#pragma warning restore CS0618 // Type or member is obsolete ServerName = _applicationHost.FriendlyName, LocalAddress = _applicationHost.GetSmartApiUrl(request), StartupWizardCompleted = _configurationManager.CommonConfiguration.IsStartupWizardCompleted, @@ -73,6 +82,29 @@ public class SystemManager : ISystemManager }; } + /// + public SystemStorageInfo GetSystemStorageInfo() + { + var virtualFolderInfos = _libraryManager.GetVirtualFolders().Select(e => new LibraryStorageInfo() + { + Id = Guid.Parse(e.ItemId), + Name = e.Name, + Folders = e.Locations.Select(f => StorageHelper.GetFreeSpaceOf(f)).ToArray() + }); + + return new SystemStorageInfo() + { + ProgramDataFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.ProgramDataPath), + WebFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.WebPath), + LogFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.LogDirectoryPath), + ImageCacheFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.ImageCachePath), + InternalMetadataFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.InternalMetadataPath), + CacheFolder = StorageHelper.GetFreeSpaceOf(_applicationPaths.CachePath), + TranscodingTempFolder = StorageHelper.GetFreeSpaceOf(_configurationManager.GetTranscodePath()), + Libraries = virtualFolderInfos.ToArray() + }; + } + /// public PublicSystemInfo GetPublicSystemInfo(HttpRequest request) { diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 0ee11c070..07a1f7650 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Net.Mime; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; +using Jellyfin.Api.Models.SystemInfoDtos; using MediaBrowser.Common.Api; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; @@ -71,6 +72,19 @@ public class SystemController : BaseJellyfinApiController public ActionResult GetSystemInfo() => _systemManager.GetSystemInfo(Request); + /// + /// Gets information about the server. + /// + /// Information retrieved. + /// User does not have permission to retrieve information. + /// A with info about the system. + [HttpGet("Info/Storage")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public ActionResult GetSystemStorage() + => Ok(SystemStorageDto.FromSystemStorageInfo(_systemManager.GetSystemStorageInfo())); + /// /// Gets public information about the server. /// diff --git a/Jellyfin.Api/Models/SystemInfoDtos/FolderStorageDto.cs b/Jellyfin.Api/Models/SystemInfoDtos/FolderStorageDto.cs new file mode 100644 index 000000000..00a965898 --- /dev/null +++ b/Jellyfin.Api/Models/SystemInfoDtos/FolderStorageDto.cs @@ -0,0 +1,46 @@ +using MediaBrowser.Model.System; + +namespace Jellyfin.Api.Models.SystemInfoDtos; + +/// +/// Contains information about a specific folder. +/// +public record FolderStorageDto +{ + /// + /// Gets the path of the folder in question. + /// + public required string Path { get; init; } + + /// + /// Gets the free space of the underlying storage device of the . + /// + public long FreeSpace { get; init; } + + /// + /// Gets the used space of the underlying storage device of the . + /// + public long UsedSpace { get; init; } + + /// + /// Gets the kind of storage device of the . + /// + public string? StorageType { get; init; } + + /// + /// Gets the Device Identifier. + /// + public string? DeviceId { get; init; } + + internal static FolderStorageDto FromFolderStorageInfo(FolderStorageInfo model) + { + return new() + { + Path = model.Path, + FreeSpace = model.FreeSpace, + UsedSpace = model.UsedSpace, + StorageType = model.StorageType, + DeviceId = model.DeviceId + }; + } +} diff --git a/Jellyfin.Api/Models/SystemInfoDtos/LibraryStorageDto.cs b/Jellyfin.Api/Models/SystemInfoDtos/LibraryStorageDto.cs new file mode 100644 index 000000000..c138324d2 --- /dev/null +++ b/Jellyfin.Api/Models/SystemInfoDtos/LibraryStorageDto.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using MediaBrowser.Model.System; + +namespace Jellyfin.Api.Models.SystemInfoDtos; + +/// +/// Contains informations about a libraries storage informations. +/// +public record LibraryStorageDto +{ + /// + /// Gets or sets the Library Id. + /// + public required Guid Id { get; set; } + + /// + /// Gets or sets the name of the library. + /// + public required string Name { get; set; } + + /// + /// Gets or sets the storage informations about the folders used in a library. + /// + public required IReadOnlyCollection Folders { get; set; } + + internal static LibraryStorageDto FromLibraryStorageModel(LibraryStorageInfo model) + { + return new() + { + Id = model.Id, + Name = model.Name, + Folders = model.Folders.Select(FolderStorageDto.FromFolderStorageInfo).ToArray() + }; + } +} diff --git a/Jellyfin.Api/Models/SystemInfoDtos/SystemStorageDto.cs b/Jellyfin.Api/Models/SystemInfoDtos/SystemStorageDto.cs new file mode 100644 index 000000000..a09042439 --- /dev/null +++ b/Jellyfin.Api/Models/SystemInfoDtos/SystemStorageDto.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using MediaBrowser.Model.System; + +namespace Jellyfin.Api.Models.SystemInfoDtos; + +/// +/// Contains informations about the systems storage. +/// +public record SystemStorageDto +{ + /// + /// Gets or sets the Storage information of the program data folder. + /// + public required FolderStorageDto ProgramDataFolder { get; set; } + + /// + /// Gets or sets the Storage information of the web UI resources folder. + /// + public required FolderStorageDto WebFolder { get; set; } + + /// + /// Gets or sets the Storage information of the folder where images are cached. + /// + public required FolderStorageDto ImageCacheFolder { get; set; } + + /// + /// Gets or sets the Storage information of the cache folder. + /// + public required FolderStorageDto CacheFolder { get; set; } + + /// + /// Gets or sets the Storage information of the folder where logfiles are saved to. + /// + public required FolderStorageDto LogFolder { get; set; } + + /// + /// Gets or sets the Storage information of the folder where metadata is stored. + /// + public required FolderStorageDto InternalMetadataFolder { get; set; } + + /// + /// Gets or sets the Storage information of the transcoding cache. + /// + public required FolderStorageDto TranscodingTempFolder { get; set; } + + /// + /// Gets or sets the storage informations of all libraries. + /// + public required IReadOnlyCollection Libraries { get; set; } + + internal static SystemStorageDto FromSystemStorageInfo(SystemStorageInfo model) + { + return new SystemStorageDto() + { + ProgramDataFolder = FolderStorageDto.FromFolderStorageInfo(model.ProgramDataFolder), + WebFolder = FolderStorageDto.FromFolderStorageInfo(model.WebFolder), + ImageCacheFolder = FolderStorageDto.FromFolderStorageInfo(model.ImageCacheFolder), + CacheFolder = FolderStorageDto.FromFolderStorageInfo(model.CacheFolder), + LogFolder = FolderStorageDto.FromFolderStorageInfo(model.LogFolder), + InternalMetadataFolder = FolderStorageDto.FromFolderStorageInfo(model.InternalMetadataFolder), + TranscodingTempFolder = FolderStorageDto.FromFolderStorageInfo(model.TranscodingTempFolder), + Libraries = model.Libraries.Select(LibraryStorageDto.FromLibraryStorageModel).ToArray() + }; + } +} diff --git a/Jellyfin.Server.Implementations/StorageHelpers/StorageHelper.cs b/Jellyfin.Server.Implementations/StorageHelpers/StorageHelper.cs new file mode 100644 index 000000000..635644179 --- /dev/null +++ b/Jellyfin.Server.Implementations/StorageHelpers/StorageHelper.cs @@ -0,0 +1,109 @@ +using System; +using System.Globalization; +using System.IO; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.System; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Implementations.StorageHelpers; + +/// +/// Contains methods to help with checking for storage and returning storage data for jellyfin folders. +/// +public static class StorageHelper +{ + private const long TwoGigabyte = 2_147_483_647L; + private const long FiveHundredAndTwelveMegaByte = 536_870_911L; + private static readonly string[] _byteHumanizedSuffixes = ["B", "KB", "MB", "GB", "TB", "PB", "EB"]; + + /// + /// Tests the available storage capacity on the jellyfin paths with estimated minimum values. + /// + /// The application paths. + /// Logger. + public static void TestCommonPathsForStorageCapacity(IApplicationPaths applicationPaths, ILogger logger) + { + TestDataDirectorySize(applicationPaths.DataPath, logger, TwoGigabyte); + TestDataDirectorySize(applicationPaths.LogDirectoryPath, logger, FiveHundredAndTwelveMegaByte); + TestDataDirectorySize(applicationPaths.CachePath, logger, TwoGigabyte); + TestDataDirectorySize(applicationPaths.ProgramDataPath, logger, TwoGigabyte); + TestDataDirectorySize(applicationPaths.TempDirectory, logger, TwoGigabyte); + } + + /// + /// Gets the free space of a specific directory. + /// + /// Path to a folder. + /// The number of bytes available space. + public static FolderStorageInfo GetFreeSpaceOf(string path) + { + try + { + var driveInfo = new DriveInfo(path); + return new FolderStorageInfo() + { + Path = path, + FreeSpace = driveInfo.AvailableFreeSpace, + UsedSpace = driveInfo.TotalSize - driveInfo.AvailableFreeSpace, + StorageType = driveInfo.DriveType.ToString(), + DeviceId = driveInfo.Name, + }; + } + catch + { + return new FolderStorageInfo() + { + Path = path, + FreeSpace = -1, + UsedSpace = -1, + StorageType = null, + DeviceId = null + }; + } + } + + /// + /// Gets the underlying drive data from a given path and checks if the available storage capacity matches the threshold. + /// + /// The path to a folder to evaluate. + /// The logger. + /// The threshold to check for or -1 to just log the data. + /// Thrown when the threshold is not available on the underlying storage. + private static void TestDataDirectorySize(string path, ILogger logger, long threshold = -1) + { + logger.LogDebug("Check path {TestPath} for storage capacity", path); + var drive = new DriveInfo(path); + if (threshold != -1 && drive.AvailableFreeSpace < threshold) + { + throw new InvalidOperationException($"The path `{path}` has insufficient free space. Required: at least {HumanizeStorageSize(threshold)}."); + } + + logger.LogInformation( + "Storage path `{TestPath}` ({StorageType}) successfully checked with {FreeSpace} free which is over the minimum of {MinFree}.", + path, + drive.DriveType, + HumanizeStorageSize(drive.AvailableFreeSpace), + HumanizeStorageSize(threshold)); + } + + /// + /// Formats a size in bytes into a common human readable form. + /// + /// + /// Taken and slightly modified from https://stackoverflow.com/a/4975942/1786007 . + /// + /// The size in bytes. + /// A human readable approximate representation of the argument. + public static string HumanizeStorageSize(long byteCount) + { + if (byteCount == 0) + { + return $"0{_byteHumanizedSuffixes[0]}"; + } + + var bytes = Math.Abs(byteCount); + var place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024))); + var num = Math.Round(bytes / Math.Pow(1024, place), 1); + return (Math.Sign(byteCount) * num).ToString(CultureInfo.InvariantCulture) + _byteHumanizedSuffixes[place]; + } +} diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 55a4a0087..8d0bf73f6 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -11,6 +12,7 @@ using Emby.Server.Implementations; using Jellyfin.Database.Implementations; using Jellyfin.Server.Extensions; using Jellyfin.Server.Helpers; +using Jellyfin.Server.Implementations.StorageHelpers; using Jellyfin.Server.ServerSetupApp; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; @@ -120,6 +122,8 @@ namespace Jellyfin.Server } } + StorageHelper.TestCommonPathsForStorageCapacity(appPaths, _loggerFactory.CreateLogger()); + StartupHelpers.PerformStaticInitialization(); await Migrations.MigrationRunner.RunPreStartup(appPaths, _loggerFactory).ConfigureAwait(false); diff --git a/MediaBrowser.Controller/ISystemManager.cs b/MediaBrowser.Controller/ISystemManager.cs index ef3034d2f..08344a1e5 100644 --- a/MediaBrowser.Controller/ISystemManager.cs +++ b/MediaBrowser.Controller/ISystemManager.cs @@ -1,5 +1,6 @@ using MediaBrowser.Model.System; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; namespace MediaBrowser.Controller; @@ -31,4 +32,10 @@ public interface ISystemManager /// Starts the application shutdown process. /// void Shutdown(); + + /// + /// Gets the systems storage resources. + /// + /// The . + SystemStorageInfo GetSystemStorageInfo(); } diff --git a/MediaBrowser.Model/System/FolderStorageInfo.cs b/MediaBrowser.Model/System/FolderStorageInfo.cs new file mode 100644 index 000000000..7b10e4ea5 --- /dev/null +++ b/MediaBrowser.Model/System/FolderStorageInfo.cs @@ -0,0 +1,32 @@ +namespace MediaBrowser.Model.System; + +/// +/// Contains information about a specific folder. +/// +public record FolderStorageInfo +{ + /// + /// Gets the path of the folder in question. + /// + public required string Path { get; init; } + + /// + /// Gets the free space of the underlying storage device of the . + /// + public long FreeSpace { get; init; } + + /// + /// Gets the used space of the underlying storage device of the . + /// + public long UsedSpace { get; init; } + + /// + /// Gets the kind of storage device of the . + /// + public string? StorageType { get; init; } + + /// + /// Gets the Device Identifier. + /// + public string? DeviceId { get; init; } +} diff --git a/MediaBrowser.Model/System/LibraryStorageInfo.cs b/MediaBrowser.Model/System/LibraryStorageInfo.cs new file mode 100644 index 000000000..d4111b29c --- /dev/null +++ b/MediaBrowser.Model/System/LibraryStorageInfo.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; + +namespace MediaBrowser.Model.System; + +/// +/// Contains informations about a libraries storage informations. +/// +public class LibraryStorageInfo +{ + /// + /// Gets or sets the Library Id. + /// + public required Guid Id { get; set; } + + /// + /// Gets or sets the name of the library. + /// + public required string Name { get; set; } + + /// + /// Gets or sets the storage informations about the folders used in a library. + /// + public required IReadOnlyCollection Folders { get; set; } +} diff --git a/MediaBrowser.Model/System/SystemInfo.cs b/MediaBrowser.Model/System/SystemInfo.cs index f37ac6a14..232a2a6bc 100644 --- a/MediaBrowser.Model/System/SystemInfo.cs +++ b/MediaBrowser.Model/System/SystemInfo.cs @@ -6,133 +6,139 @@ using System.Collections.Generic; using System.ComponentModel; using MediaBrowser.Model.Updates; -namespace MediaBrowser.Model.System +namespace MediaBrowser.Model.System; + +/// +/// Class SystemInfo. +/// +public class SystemInfo : PublicSystemInfo { /// - /// Class SystemInfo. + /// Initializes a new instance of the class. /// - public class SystemInfo : PublicSystemInfo + public SystemInfo() { - /// - /// Initializes a new instance of the class. - /// - public SystemInfo() - { - CompletedInstallations = Array.Empty(); - } - - /// - /// Gets or sets the display name of the operating system. - /// - /// The display name of the operating system. - [Obsolete("This is no longer set")] - public string OperatingSystemDisplayName { get; set; } = string.Empty; - - /// - /// Gets or sets the package name. - /// - /// The value of the '-package' command line argument. - public string PackageName { get; set; } - - /// - /// Gets or sets a value indicating whether this instance has pending restart. - /// - /// true if this instance has pending restart; otherwise, false. - public bool HasPendingRestart { get; set; } - - public bool IsShuttingDown { get; set; } - - /// - /// Gets or sets a value indicating whether [supports library monitor]. - /// - /// true if [supports library monitor]; otherwise, false. - public bool SupportsLibraryMonitor { get; set; } - - /// - /// Gets or sets the web socket port number. - /// - /// The web socket port number. - public int WebSocketPortNumber { get; set; } - - /// - /// Gets or sets the completed installations. - /// - /// The completed installations. - public InstallationInfo[] CompletedInstallations { get; set; } - - /// - /// Gets or sets a value indicating whether this instance can self restart. - /// - /// true. - [Obsolete("This is always true")] - [DefaultValue(true)] - public bool CanSelfRestart { get; set; } = true; - - [Obsolete("This is always false")] - [DefaultValue(false)] - public bool CanLaunchWebBrowser { get; set; } = false; - - /// - /// Gets or sets the program data path. - /// - /// The program data path. - public string ProgramDataPath { get; set; } - - /// - /// Gets or sets the web UI resources path. - /// - /// The web UI resources path. - public string WebPath { get; set; } - - /// - /// Gets or sets the items by name path. - /// - /// The items by name path. - public string ItemsByNamePath { get; set; } - - /// - /// Gets or sets the cache path. - /// - /// The cache path. - public string CachePath { get; set; } - - /// - /// Gets or sets the log path. - /// - /// The log path. - public string LogPath { get; set; } - - /// - /// Gets or sets the internal metadata path. - /// - /// The internal metadata path. - public string InternalMetadataPath { get; set; } - - /// - /// Gets or sets the transcode path. - /// - /// The transcode path. - public string TranscodingTempPath { get; set; } - - /// - /// Gets or sets the list of cast receiver applications. - /// - public IReadOnlyList CastReceiverApplications { get; set; } - - /// - /// Gets or sets a value indicating whether this instance has update available. - /// - /// true if this instance has update available; otherwise, false. - [Obsolete("This should be handled by the package manager")] - [DefaultValue(false)] - public bool HasUpdateAvailable { get; set; } - - [Obsolete("This isn't set correctly anymore")] - [DefaultValue("System")] - public string EncoderLocation { get; set; } = "System"; - - [Obsolete("This is no longer set")] - [DefaultValue("X64")] - public string SystemArchitecture { get; set; } = "X64"; + CompletedInstallations = Array.Empty(); } + + /// + /// Gets or sets the display name of the operating system. + /// + /// The display name of the operating system. + [Obsolete("This is no longer set")] + public string OperatingSystemDisplayName { get; set; } = string.Empty; + + /// + /// Gets or sets the package name. + /// + /// The value of the '-package' command line argument. + public string PackageName { get; set; } + + /// + /// Gets or sets a value indicating whether this instance has pending restart. + /// + /// true if this instance has pending restart; otherwise, false. + public bool HasPendingRestart { get; set; } + + public bool IsShuttingDown { get; set; } + + /// + /// Gets or sets a value indicating whether [supports library monitor]. + /// + /// true if [supports library monitor]; otherwise, false. + public bool SupportsLibraryMonitor { get; set; } + + /// + /// Gets or sets the web socket port number. + /// + /// The web socket port number. + public int WebSocketPortNumber { get; set; } + + /// + /// Gets or sets the completed installations. + /// + /// The completed installations. + public InstallationInfo[] CompletedInstallations { get; set; } + + /// + /// Gets or sets a value indicating whether this instance can self restart. + /// + /// true. + [Obsolete("This is always true")] + [DefaultValue(true)] + public bool CanSelfRestart { get; set; } = true; + + [Obsolete("This is always false")] + [DefaultValue(false)] + public bool CanLaunchWebBrowser { get; set; } = false; + + /// + /// Gets or sets the program data path. + /// + /// The program data path. + [Obsolete("Use the newer SystemStorageDto instead")] + public string ProgramDataPath { get; set; } + + /// + /// Gets or sets the web UI resources path. + /// + /// The web UI resources path. + [Obsolete("Use the newer SystemStorageDto instead")] + public string WebPath { get; set; } + + /// + /// Gets or sets the items by name path. + /// + /// The items by name path. + [Obsolete("Use the newer SystemStorageDto instead")] + public string ItemsByNamePath { get; set; } + + /// + /// Gets or sets the cache path. + /// + /// The cache path. + [Obsolete("Use the newer SystemStorageDto instead")] + public string CachePath { get; set; } + + /// + /// Gets or sets the log path. + /// + /// The log path. + [Obsolete("Use the newer SystemStorageDto instead")] + public string LogPath { get; set; } + + /// + /// Gets or sets the internal metadata path. + /// + /// The internal metadata path. + [Obsolete("Use the newer SystemStorageDto instead")] + public string InternalMetadataPath { get; set; } + + /// + /// Gets or sets the transcode path. + /// + /// The transcode path. + [Obsolete("Use the newer SystemStorageDto instead")] + public string TranscodingTempPath { get; set; } + + /// + /// Gets or sets the list of cast receiver applications. + /// + public IReadOnlyList CastReceiverApplications { get; set; } + + /// + /// Gets or sets a value indicating whether this instance has update available. + /// + /// true if this instance has update available; otherwise, false. + [Obsolete("This should be handled by the package manager")] + [DefaultValue(false)] + public bool HasUpdateAvailable { get; set; } + + [Obsolete("This isn't set correctly anymore")] + [DefaultValue("System")] + public string EncoderLocation { get; set; } = "System"; + + [Obsolete("This is no longer set")] + [DefaultValue("X64")] + public string SystemArchitecture { get; set; } = "X64"; } diff --git a/MediaBrowser.Model/System/SystemStorageInfo.cs b/MediaBrowser.Model/System/SystemStorageInfo.cs new file mode 100644 index 000000000..42e7a37e0 --- /dev/null +++ b/MediaBrowser.Model/System/SystemStorageInfo.cs @@ -0,0 +1,56 @@ +using System.Collections.Generic; + +namespace MediaBrowser.Model.System; + +/// +/// Contains informations about the systems storage. +/// +public class SystemStorageInfo +{ + /// + /// Gets or sets the program data path. + /// + /// The program data path. + public required FolderStorageInfo ProgramDataFolder { get; set; } + + /// + /// Gets or sets the web UI resources path. + /// + /// The web UI resources path. + public required FolderStorageInfo WebFolder { get; set; } + + /// + /// Gets or sets the items by name path. + /// + /// The items by name path. + public required FolderStorageInfo ImageCacheFolder { get; set; } + + /// + /// Gets or sets the cache path. + /// + /// The cache path. + public required FolderStorageInfo CacheFolder { get; set; } + + /// + /// Gets or sets the log path. + /// + /// The log path. + public required FolderStorageInfo LogFolder { get; set; } + + /// + /// Gets or sets the internal metadata path. + /// + /// The internal metadata path. + public required FolderStorageInfo InternalMetadataFolder { get; set; } + + /// + /// Gets or sets the transcode path. + /// + /// The transcode path. + public required FolderStorageInfo TranscodingTempFolder { get; set; } + + /// + /// Gets or sets the storage informations of all libraries. + /// + public required IReadOnlyCollection Libraries { get; set; } +} -- cgit v1.2.3 From fe2596dc0e389c0496a384cc1893fddd4742ed37 Mon Sep 17 00:00:00 2001 From: JPVenson Date: Mon, 19 May 2025 03:39:04 +0300 Subject: Add Full system backup feature (#13945) --- .../AppBase/BaseApplicationPaths.cs | 3 + Emby.Server.Implementations/ApplicationHost.cs | 5 + Jellyfin.Api/Controllers/BackupController.cs | 127 ++++++ Jellyfin.Api/Controllers/SystemController.cs | 1 - .../FullSystemBackup/BackupManifest.cs | 19 + .../FullSystemBackup/BackupOptions.cs | 13 + .../FullSystemBackup/BackupService.cs | 463 +++++++++++++++++++++ .../Migrations/JellyfinMigrationService.cs | 43 +- Jellyfin.Server/Program.cs | 14 +- Jellyfin.Server/StartupOptions.cs | 6 + .../Configuration/IApplicationPaths.cs | 6 + MediaBrowser.Controller/IServerApplicationHost.cs | 5 + .../SystemBackupService/BackupManifestDto.cs | 34 ++ .../SystemBackupService/BackupOptionsDto.cs | 24 ++ .../SystemBackupService/BackupRestoreRequestDto.cs | 15 + .../SystemBackupService/IBackupService.cs | 48 +++ .../Entities/TrickplayInfo.cs | 1 - .../Entities/User.cs | 1 - .../IJellyfinDatabaseProvider.cs | 9 + .../SqliteDatabaseProvider.cs | 24 +- .../Controllers/SystemControllerTests.cs | 1 + 21 files changed, 841 insertions(+), 21 deletions(-) create mode 100644 Jellyfin.Api/Controllers/BackupController.cs create mode 100644 Jellyfin.Server.Implementations/FullSystemBackup/BackupManifest.cs create mode 100644 Jellyfin.Server.Implementations/FullSystemBackup/BackupOptions.cs create mode 100644 Jellyfin.Server.Implementations/FullSystemBackup/BackupService.cs create mode 100644 MediaBrowser.Controller/SystemBackupService/BackupManifestDto.cs create mode 100644 MediaBrowser.Controller/SystemBackupService/BackupOptionsDto.cs create mode 100644 MediaBrowser.Controller/SystemBackupService/BackupRestoreRequestDto.cs create mode 100644 MediaBrowser.Controller/SystemBackupService/IBackupService.cs (limited to 'Jellyfin.Api/Controllers/SystemController.cs') diff --git a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs index 18ebd628d..e74755ec3 100644 --- a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs +++ b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs @@ -78,6 +78,9 @@ namespace Emby.Server.Implementations.AppBase /// public string TrickplayPath => Path.Combine(DataPath, "trickplay"); + /// + public string BackupPath => Path.Combine(DataPath, "backups"); + /// public virtual void MakeSanityCheckOrThrow() { diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index c397a69fb..565d0f0c8 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -40,8 +40,10 @@ using Jellyfin.Drawing; using Jellyfin.MediaEncoding.Hls.Playlist; using Jellyfin.Networking.Manager; using Jellyfin.Networking.Udp; +using Jellyfin.Server.Implementations.FullSystemBackup; using Jellyfin.Server.Implementations.Item; using Jellyfin.Server.Implementations.MediaSegments; +using Jellyfin.Server.Implementations.SystemBackupService; using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; @@ -268,6 +270,8 @@ namespace Emby.Server.Implementations ? Environment.MachineName : ConfigurationManager.Configuration.ServerName; + public string RestoreBackupPath { get; set; } + public string ExpandVirtualPath(string path) { if (path is null) @@ -472,6 +476,7 @@ namespace Emby.Server.Implementations serviceCollection.AddSingleton(this); serviceCollection.AddSingleton(_pluginManager); serviceCollection.AddSingleton(ApplicationPaths); + serviceCollection.AddSingleton(); serviceCollection.AddSingleton(); serviceCollection.AddSingleton(); diff --git a/Jellyfin.Api/Controllers/BackupController.cs b/Jellyfin.Api/Controllers/BackupController.cs new file mode 100644 index 000000000..aa908ee30 --- /dev/null +++ b/Jellyfin.Api/Controllers/BackupController.cs @@ -0,0 +1,127 @@ +using System.IO; +using System.Threading.Tasks; +using Jellyfin.Server.Implementations.SystemBackupService; +using MediaBrowser.Common.Api; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.SystemBackupService; +using Microsoft.AspNetCore.Authentication.OAuth.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; + +namespace Jellyfin.Api.Controllers; + +/// +/// The backup controller. +/// +[Authorize(Policy = Policies.RequiresElevation)] +public class BackupController : BaseJellyfinApiController +{ + private readonly IBackupService _backupService; + private readonly IApplicationPaths _applicationPaths; + + /// + /// Initializes a new instance of the class. + /// + /// Instance of the interface. + /// Instance of the interface. + public BackupController(IBackupService backupService, IApplicationPaths applicationPaths) + { + _backupService = backupService; + _applicationPaths = applicationPaths; + } + + /// + /// Creates a new Backup. + /// + /// The backup options. + /// Backup created. + /// User does not have permission to retrieve information. + /// The created backup manifest. + [HttpPost("Create")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task> CreateBackup([FromBody] BackupOptionsDto backupOptions) + { + return Ok(await _backupService.CreateBackupAsync(backupOptions ?? new()).ConfigureAwait(false)); + } + + /// + /// Restores to a backup by restarting the server and applying the backup. + /// + /// The data to start a restore process. + /// Backup restore started. + /// User does not have permission to retrieve information. + /// No-Content. + [HttpPost("Restore")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public IActionResult StartRestoreBackup([FromBody, BindRequired] BackupRestoreRequestDto archiveRestoreDto) + { + var archivePath = SanitizePath(archiveRestoreDto.ArchiveFileName); + if (!System.IO.File.Exists(archivePath)) + { + return NotFound(); + } + + _backupService.ScheduleRestoreAndRestartServer(archivePath); + return NoContent(); + } + + /// + /// Gets a list of all currently present backups in the backup directory. + /// + /// Backups available. + /// User does not have permission to retrieve information. + /// The list of backups. + [HttpGet] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task> ListBackups() + { + return Ok(await _backupService.EnumerateBackups().ConfigureAwait(false)); + } + + /// + /// Gets the descriptor from an existing archive is present. + /// + /// The data to start a restore process. + /// Backup archive manifest. + /// Not a valid jellyfin Archive. + /// Not a valid path. + /// User does not have permission to retrieve information. + /// The backup manifest. + [HttpGet("Manifest")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task> GetBackup([BindRequired] string path) + { + var backupPath = SanitizePath(path); + + if (!System.IO.File.Exists(backupPath)) + { + return NotFound(); + } + + var manifest = await _backupService.GetBackupManifest(backupPath).ConfigureAwait(false); + if (manifest is null) + { + return NoContent(); + } + + return Ok(manifest); + } + + [NonAction] + private string SanitizePath(string path) + { + // sanitize path + var archiveRestorePath = Path.GetFileName(Path.GetFullPath(path)); + var archivePath = Path.Combine(_applicationPaths.BackupPath, archiveRestorePath); + return archivePath; + } +} diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 07a1f7650..450225c37 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -5,7 +5,6 @@ using System.IO; using System.Linq; using System.Net.Mime; using Jellyfin.Api.Attributes; -using Jellyfin.Api.Constants; using Jellyfin.Api.Models.SystemInfoDtos; using MediaBrowser.Common.Api; using MediaBrowser.Common.Configuration; diff --git a/Jellyfin.Server.Implementations/FullSystemBackup/BackupManifest.cs b/Jellyfin.Server.Implementations/FullSystemBackup/BackupManifest.cs new file mode 100644 index 000000000..77a49b2b5 --- /dev/null +++ b/Jellyfin.Server.Implementations/FullSystemBackup/BackupManifest.cs @@ -0,0 +1,19 @@ +using System; + +namespace Jellyfin.Server.Implementations.FullSystemBackup; + +/// +/// Manifest type for backups internal structure. +/// +internal class BackupManifest +{ + public required Version ServerVersion { get; set; } + + public required Version BackupEngineVersion { get; set; } + + public required DateTimeOffset DateCreated { get; set; } + + public required string[] DatabaseTables { get; set; } + + public required BackupOptions Options { get; set; } +} diff --git a/Jellyfin.Server.Implementations/FullSystemBackup/BackupOptions.cs b/Jellyfin.Server.Implementations/FullSystemBackup/BackupOptions.cs new file mode 100644 index 000000000..706f009ac --- /dev/null +++ b/Jellyfin.Server.Implementations/FullSystemBackup/BackupOptions.cs @@ -0,0 +1,13 @@ +namespace Jellyfin.Server.Implementations.FullSystemBackup; + +/// +/// Defines the optional contents of the backup archive. +/// +internal class BackupOptions +{ + public bool Metadata { get; set; } + + public bool Trickplay { get; set; } + + public bool Subtitles { get; set; } +} diff --git a/Jellyfin.Server.Implementations/FullSystemBackup/BackupService.cs b/Jellyfin.Server.Implementations/FullSystemBackup/BackupService.cs new file mode 100644 index 000000000..c3f5b0103 --- /dev/null +++ b/Jellyfin.Server.Implementations/FullSystemBackup/BackupService.cs @@ -0,0 +1,463 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Database.Implementations; +using Jellyfin.Server.Implementations.StorageHelpers; +using Jellyfin.Server.Implementations.SystemBackupService; +using MediaBrowser.Controller; +using MediaBrowser.Controller.SystemBackupService; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Implementations.FullSystemBackup; + +/// +/// Contains methods for creating and restoring backups. +/// +public class BackupService : IBackupService +{ + private const string ManifestEntryName = "manifest.json"; + private readonly ILogger _logger; + private readonly IDbContextFactory _dbProvider; + private readonly IServerApplicationHost _applicationHost; + private readonly IServerApplicationPaths _applicationPaths; + private readonly IJellyfinDatabaseProvider _jellyfinDatabaseProvider; + private static readonly JsonSerializerOptions _serializerSettings = new JsonSerializerOptions(JsonSerializerDefaults.General) + { + AllowTrailingCommas = true, + ReferenceHandler = ReferenceHandler.IgnoreCycles, + }; + + private readonly Version _backupEngineVersion = Version.Parse("0.1.0"); + + /// + /// Initializes a new instance of the class. + /// + /// A logger. + /// A Database Factory. + /// The Application host. + /// The application paths. + /// The Jellyfin database Provider in use. + public BackupService( + ILogger logger, + IDbContextFactory dbProvider, + IServerApplicationHost applicationHost, + IServerApplicationPaths applicationPaths, + IJellyfinDatabaseProvider jellyfinDatabaseProvider) + { + _logger = logger; + _dbProvider = dbProvider; + _applicationHost = applicationHost; + _applicationPaths = applicationPaths; + _jellyfinDatabaseProvider = jellyfinDatabaseProvider; + } + + /// + public void ScheduleRestoreAndRestartServer(string archivePath) + { + _applicationHost.RestoreBackupPath = archivePath; + _applicationHost.ShouldRestart = true; + _applicationHost.NotifyPendingRestart(); + } + + /// + public async Task RestoreBackupAsync(string archivePath) + { + _logger.LogWarning("Begin restoring system to {BackupArchive}", archivePath); // Info isn't cutting it + if (!File.Exists(archivePath)) + { + throw new FileNotFoundException($"Requested backup file '{archivePath}' does not exist."); + } + + StorageHelper.TestCommonPathsForStorageCapacity(_applicationPaths, _logger); + + var fileStream = File.OpenRead(archivePath); + await using (fileStream.ConfigureAwait(false)) + { + using var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Read, false); + var zipArchiveEntry = zipArchive.GetEntry(ManifestEntryName); + + if (zipArchiveEntry is null) + { + throw new NotSupportedException($"The loaded archive '{archivePath}' does not appear to be a Jellyfin backup as its missing the '{ManifestEntryName}'."); + } + + BackupManifest? manifest; + var manifestStream = zipArchiveEntry.Open(); + await using (manifestStream.ConfigureAwait(false)) + { + manifest = await JsonSerializer.DeserializeAsync(manifestStream, _serializerSettings).ConfigureAwait(false); + } + + if (manifest!.ServerVersion > _applicationHost.ApplicationVersion) // newer versions of Jellyfin should be able to load older versions as we have migrations. + { + throw new NotSupportedException($"The loaded archive '{archivePath}' is made for a newer version of Jellyfin ({manifest.ServerVersion}) and cannot be loaded in this version."); + } + + if (!TestBackupVersionCompatibility(manifest.BackupEngineVersion)) + { + throw new NotSupportedException($"The loaded archive '{archivePath}' is made for a newer version of Jellyfin ({manifest.ServerVersion}) and cannot be loaded in this version."); + } + + void CopyDirectory(string source, string target) + { + source = Path.GetFullPath(source); + Directory.CreateDirectory(source); + + foreach (var item in zipArchive.Entries) + { + var sanitizedSourcePath = Path.GetFullPath(item.FullName.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar); + if (!sanitizedSourcePath.StartsWith(target, StringComparison.Ordinal)) + { + continue; + } + + var targetPath = Path.Combine(source, sanitizedSourcePath[target.Length..].Trim('/')); + _logger.LogInformation("Restore and override {File}", targetPath); + item.ExtractToFile(targetPath); + } + } + + CopyDirectory(_applicationPaths.ConfigurationDirectoryPath, "Config/"); + CopyDirectory(_applicationPaths.DataPath, "Data/"); + CopyDirectory(_applicationPaths.RootFolderPath, "Root/"); + + _logger.LogInformation("Begin restoring Database"); + var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false); + await using (dbContext.ConfigureAwait(false)) + { + dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; + var entityTypes = typeof(JellyfinDbContext).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance) + .Where(e => e.PropertyType.IsAssignableTo(typeof(IQueryable))) + .Select(e => (Type: e, Set: e.GetValue(dbContext) as IQueryable)) + .ToArray(); + + var tableNames = entityTypes.Select(f => dbContext.Model.FindEntityType(f.Type.PropertyType.GetGenericArguments()[0])!.GetSchemaQualifiedTableName()!); + _logger.LogInformation("Begin purging database"); + await _jellyfinDatabaseProvider.PurgeDatabase(dbContext, tableNames).ConfigureAwait(false); + _logger.LogInformation("Database Purged"); + + foreach (var entityType in entityTypes) + { + _logger.LogInformation("Read backup of {Table}", entityType.Type.Name); + + var zipEntry = zipArchive.GetEntry($"Database\\{entityType.Type.Name}.json"); + if (zipEntry is null) + { + _logger.LogInformation("No backup of expected table {Table} is present in backup. Continue anyway.", entityType.Type.Name); + continue; + } + + var zipEntryStream = zipEntry.Open(); + await using (zipEntryStream.ConfigureAwait(false)) + { + _logger.LogInformation("Restore backup of {Table}", entityType.Type.Name); + var records = 0; + await foreach (var item in JsonSerializer.DeserializeAsyncEnumerable(zipEntryStream, _serializerSettings).ConfigureAwait(false)!) + { + var entity = item.Deserialize(entityType.Type.PropertyType.GetGenericArguments()[0]); + if (entity is null) + { + throw new InvalidOperationException($"Cannot deserialize entity '{item}'"); + } + + try + { + records++; + dbContext.Add(entity); + } + catch (Exception ex) + { + _logger.LogError(ex, "Could not store entity {Entity} continue anyway.", item); + } + } + + _logger.LogInformation("Prepared to restore {Number} entries for {Table}", records, entityType.Type.Name); + } + } + + _logger.LogInformation("Try restore Database"); + await dbContext.SaveChangesAsync().ConfigureAwait(false); + _logger.LogInformation("Restored database."); + } + + _logger.LogInformation("Restored Jellyfin system from {Date}.", manifest.DateCreated); + } + } + + private bool TestBackupVersionCompatibility(Version backupEngineVersion) + { + if (backupEngineVersion == _backupEngineVersion) + { + return true; + } + + return false; + } + + /// + public async Task CreateBackupAsync(BackupOptionsDto backupOptions) + { + var manifest = new BackupManifest() + { + DateCreated = DateTime.UtcNow, + ServerVersion = _applicationHost.ApplicationVersion, + DatabaseTables = null!, + BackupEngineVersion = _backupEngineVersion, + Options = Map(backupOptions) + }; + + await _jellyfinDatabaseProvider.RunScheduledOptimisation(CancellationToken.None).ConfigureAwait(false); + + var backupFolder = Path.Combine(_applicationPaths.BackupPath); + + if (!Directory.Exists(backupFolder)) + { + Directory.CreateDirectory(backupFolder); + } + + var backupStorageSpace = StorageHelper.GetFreeSpaceOf(_applicationPaths.BackupPath); + + const long FiveGigabyte = 5_368_709_115; + if (backupStorageSpace.FreeSpace < FiveGigabyte) + { + throw new InvalidOperationException($"The backup directory '{backupStorageSpace.Path}' does not have at least '{StorageHelper.HumanizeStorageSize(FiveGigabyte)}' free space. Cannot create backup."); + } + + var backupPath = Path.Combine(backupFolder, $"jellyfin-backup-{manifest.DateCreated.ToLocalTime():yyyyMMddHHmmss}.zip"); + _logger.LogInformation("Attempt to create a new backup at {BackupPath}", backupPath); + var fileStream = File.OpenWrite(backupPath); + await using (fileStream.ConfigureAwait(false)) + using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create, false)) + { + _logger.LogInformation("Start backup process."); + var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false); + await using (dbContext.ConfigureAwait(false)) + { + dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; + var entityTypes = typeof(JellyfinDbContext).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance) + .Where(e => e.PropertyType.IsAssignableTo(typeof(IQueryable))) + .Select(e => (Type: e, Set: e.GetValue(dbContext) as IQueryable)) + .ToArray(); + manifest.DatabaseTables = entityTypes.Select(e => e.Type.Name).ToArray(); + var transaction = await dbContext.Database.BeginTransactionAsync().ConfigureAwait(false); + + await using (transaction.ConfigureAwait(false)) + { + _logger.LogInformation("Begin Database backup"); + static IAsyncEnumerable GetValues(IQueryable dbSet, Type type) + { + var method = dbSet.GetType().GetMethod(nameof(DbSet.AsAsyncEnumerable))!; + var enumerable = method.Invoke(dbSet, null)!; + return (IAsyncEnumerable)enumerable; + } + + foreach (var entityType in entityTypes) + { + _logger.LogInformation("Begin backup of entity {Table}", entityType.Type.Name); + var zipEntry = zipArchive.CreateEntry($"Database\\{entityType.Type.Name}.json"); + var entities = 0; + var zipEntryStream = zipEntry.Open(); + await using (zipEntryStream.ConfigureAwait(false)) + { + var jsonSerializer = new Utf8JsonWriter(zipEntryStream); + await using (jsonSerializer.ConfigureAwait(false)) + { + jsonSerializer.WriteStartArray(); + + var set = GetValues(entityType.Set!, entityType.Type.PropertyType).ConfigureAwait(false); + await foreach (var item in set.ConfigureAwait(false)) + { + entities++; + try + { + JsonSerializer.SerializeToDocument(item, _serializerSettings).WriteTo(jsonSerializer); + } + catch (Exception ex) + { + _logger.LogError(ex, "Could not load entity {Entity}", item); + throw; + } + } + + jsonSerializer.WriteEndArray(); + } + } + + _logger.LogInformation("backup of entity {Table} with {Number} created", entityType.Type.Name, entities); + } + } + } + + _logger.LogInformation("Backup of folder {Table}", _applicationPaths.ConfigurationDirectoryPath); + foreach (var item in Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.xml", SearchOption.TopDirectoryOnly) + .Union(Directory.EnumerateFiles(_applicationPaths.ConfigurationDirectoryPath, "*.json", SearchOption.TopDirectoryOnly))) + { + zipArchive.CreateEntryFromFile(item, Path.Combine("Config", Path.GetFileName(item))); + } + + void CopyDirectory(string source, string target, string filter = "*") + { + if (!Directory.Exists(source)) + { + return; + } + + _logger.LogInformation("Backup of folder {Table}", source); + + foreach (var item in Directory.EnumerateFiles(source, filter, SearchOption.AllDirectories)) + { + zipArchive.CreateEntryFromFile(item, Path.Combine(target, item[..source.Length].Trim('\\'))); + } + } + + CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "users"), Path.Combine("Config", "users")); + CopyDirectory(Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks"), Path.Combine("Config", "ScheduledTasks")); + CopyDirectory(Path.Combine(_applicationPaths.RootFolderPath), "Root"); + CopyDirectory(Path.Combine(_applicationPaths.DataPath, "collections"), Path.Combine("Data", "collections")); + CopyDirectory(Path.Combine(_applicationPaths.DataPath, "playlists"), Path.Combine("Data", "playlists")); + CopyDirectory(Path.Combine(_applicationPaths.DataPath, "ScheduledTasks"), Path.Combine("Data", "ScheduledTasks")); + if (backupOptions.Subtitles) + { + CopyDirectory(Path.Combine(_applicationPaths.DataPath, "subtitles"), Path.Combine("Data", "subtitles")); + } + + if (backupOptions.Trickplay) + { + CopyDirectory(Path.Combine(_applicationPaths.DataPath, "trickplay"), Path.Combine("Data", "trickplay")); + } + + if (backupOptions.Metadata) + { + CopyDirectory(Path.Combine(_applicationPaths.InternalMetadataPath), Path.Combine("Data", "metadata")); + } + + var manifestStream = zipArchive.CreateEntry(ManifestEntryName).Open(); + await using (manifestStream.ConfigureAwait(false)) + { + await JsonSerializer.SerializeAsync(manifestStream, manifest).ConfigureAwait(false); + } + } + + _logger.LogInformation("Backup created"); + return Map(manifest, backupPath); + } + + /// + public async Task GetBackupManifest(string archivePath) + { + if (!File.Exists(archivePath)) + { + return null; + } + + BackupManifest? manifest; + try + { + manifest = await GetManifest(archivePath).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.LogError(ex, "Tried to load archive from {Path} but failed.", archivePath); + return null; + } + + if (manifest is null) + { + return null; + } + + return Map(manifest, archivePath); + } + + /// + public async Task EnumerateBackups() + { + if (!Directory.Exists(_applicationPaths.BackupPath)) + { + return []; + } + + var archives = Directory.EnumerateFiles(_applicationPaths.BackupPath, "*.zip"); + var manifests = new List(); + foreach (var item in archives) + { + try + { + var manifest = await GetManifest(item).ConfigureAwait(false); + + if (manifest is null) + { + continue; + } + + manifests.Add(Map(manifest, item)); + } + catch (Exception ex) + { + _logger.LogError(ex, "Could not load {BackupArchive} path.", item); + } + } + + return manifests.ToArray(); + } + + private static async ValueTask GetManifest(string archivePath) + { + var archiveStream = File.OpenRead(archivePath); + await using (archiveStream.ConfigureAwait(false)) + { + using var zipStream = new ZipArchive(archiveStream, ZipArchiveMode.Read); + var manifestEntry = zipStream.GetEntry(ManifestEntryName); + if (manifestEntry is null) + { + return null; + } + + var manifestStream = manifestEntry.Open(); + await using (manifestStream.ConfigureAwait(false)) + { + return await JsonSerializer.DeserializeAsync(manifestStream, _serializerSettings).ConfigureAwait(false); + } + } + } + + private static BackupManifestDto Map(BackupManifest manifest, string path) + { + return new BackupManifestDto() + { + BackupEngineVersion = manifest.BackupEngineVersion, + DateCreated = manifest.DateCreated, + ServerVersion = manifest.ServerVersion, + Path = path, + Options = Map(manifest.Options) + }; + } + + private static BackupOptionsDto Map(BackupOptions options) + { + return new BackupOptionsDto() + { + Metadata = options.Metadata, + Subtitles = options.Subtitles, + Trickplay = options.Trickplay + }; + } + + private static BackupOptions Map(BackupOptionsDto options) + { + return new BackupOptions() + { + Metadata = options.Metadata, + Subtitles = options.Subtitles, + Trickplay = options.Trickplay + }; + } +} diff --git a/Jellyfin.Server/Migrations/JellyfinMigrationService.cs b/Jellyfin.Server/Migrations/JellyfinMigrationService.cs index ebffab7ef..3d6ed73bc 100644 --- a/Jellyfin.Server/Migrations/JellyfinMigrationService.cs +++ b/Jellyfin.Server/Migrations/JellyfinMigrationService.cs @@ -7,8 +7,10 @@ using System.Threading; using System.Threading.Tasks; using Emby.Server.Implementations.Serialization; using Jellyfin.Database.Implementations; +using Jellyfin.Server.Implementations.SystemBackupService; using Jellyfin.Server.Migrations.Stages; using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.SystemBackupService; using MediaBrowser.Model.Configuration; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -103,25 +105,33 @@ internal class JellyfinMigrationService if (migrationOptions != null && migrationOptions.Applied.Count > 0) { logger.LogInformation("Old migration style migration.xml detected. Migrate now."); - var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false); - await using (dbContext.ConfigureAwait(false)) + try { - var historyRepository = dbContext.GetService(); - var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync().ConfigureAwait(false); - var oldMigrations = Migrations - .SelectMany(e => e.Where(e => e.Metadata.Key is not null)) // only consider migrations that have the key set as its the reference marker for legacy migrations. - .Where(e => migrationOptions.Applied.Any(f => f.Id.Equals(e.Metadata.Key!.Value))) - .Where(e => !appliedMigrations.Contains(e.BuildCodeMigrationId())) - .ToArray(); - var startupScripts = oldMigrations.Select(e => (Migration: e.Metadata, Script: historyRepository.GetInsertScript(new HistoryRow(e.BuildCodeMigrationId(), GetJellyfinVersion())))); - foreach (var item in startupScripts) + var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false); + await using (dbContext.ConfigureAwait(false)) { - logger.LogInformation("Migrate migration {Key}-{Name}.", item.Migration.Key, item.Migration.Name); - await dbContext.Database.ExecuteSqlRawAsync(item.Script).ConfigureAwait(false); + var historyRepository = dbContext.GetService(); + var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync().ConfigureAwait(false); + var oldMigrations = Migrations + .SelectMany(e => e.Where(e => e.Metadata.Key is not null)) // only consider migrations that have the key set as its the reference marker for legacy migrations. + .Where(e => migrationOptions.Applied.Any(f => f.Id.Equals(e.Metadata.Key!.Value))) + .Where(e => !appliedMigrations.Contains(e.BuildCodeMigrationId())) + .ToArray(); + var startupScripts = oldMigrations.Select(e => (Migration: e.Metadata, Script: historyRepository.GetInsertScript(new HistoryRow(e.BuildCodeMigrationId(), GetJellyfinVersion())))); + foreach (var item in startupScripts) + { + logger.LogInformation("Migrate migration {Key}-{Name}.", item.Migration.Key, item.Migration.Name); + await dbContext.Database.ExecuteSqlRawAsync(item.Script).ConfigureAwait(false); + } + + logger.LogInformation("Rename old migration.xml to migration.xml.backup"); + File.Move(migrationConfigPath, Path.ChangeExtension(migrationConfigPath, ".xml.backup"), true); } - - logger.LogInformation("Rename old migration.xml to migration.xml.backup"); - File.Move(migrationConfigPath, Path.ChangeExtension(migrationConfigPath, ".xml.backup"), true); + } + catch (Exception ex) + { + logger.LogCritical(ex, "Failed to apply migrations"); + throw; } } } @@ -155,6 +165,7 @@ internal class JellyfinMigrationService (string Key, IInternalMigration Migration)[] pendingMigrations = [.. pendingCodeMigrations, .. pendingDatabaseMigrations]; logger.LogInformation("There are {Pending} migrations for stage {Stage}.", pendingCodeMigrations.Length, stage); var migrations = pendingMigrations.OrderBy(e => e.Key).ToArray(); + foreach (var item in migrations) { try diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 745f92420..4584b25bd 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -16,7 +16,9 @@ using Jellyfin.Server.Extensions; using Jellyfin.Server.Helpers; using Jellyfin.Server.Implementations.DatabaseConfiguration; using Jellyfin.Server.Implementations.Extensions; +using Jellyfin.Server.Implementations.FullSystemBackup; using Jellyfin.Server.Implementations.StorageHelpers; +using Jellyfin.Server.Implementations.SystemBackupService; using Jellyfin.Server.Migrations; using Jellyfin.Server.ServerSetupApp; using MediaBrowser.Common.Configuration; @@ -58,6 +60,7 @@ namespace Jellyfin.Server private static long _startTimestamp; private static ILogger _logger = NullLogger.Instance; private static bool _restartOnShutdown; + private static string? _restoreFromBackup; /// /// The entry point of the application. @@ -79,6 +82,7 @@ namespace Jellyfin.Server private static async Task StartApp(StartupOptions options) { + _restoreFromBackup = options.RestoreArchive; _startTimestamp = Stopwatch.GetTimestamp(); ServerApplicationPaths appPaths = StartupHelpers.CreateApplicationPaths(options); appPaths.MakeSanityCheckOrThrow(); @@ -176,9 +180,16 @@ namespace Jellyfin.Server // Re-use the host service provider in the app host since ASP.NET doesn't allow a custom service collection. appHost.ServiceProvider = _jellyfinHost.Services; - PrepareDatabaseProvider(appHost.ServiceProvider); + if (!string.IsNullOrWhiteSpace(_restoreFromBackup)) + { + await appHost.ServiceProvider.GetService()!.RestoreBackupAsync(_restoreFromBackup).ConfigureAwait(false); + _restoreFromBackup = null; + _restartOnShutdown = true; + return; + } + await ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.CoreInitialisaition).ConfigureAwait(false); await appHost.InitializeServices(startupConfig).ConfigureAwait(false); @@ -209,6 +220,7 @@ namespace Jellyfin.Server await _jellyfinHost.WaitForShutdownAsync().ConfigureAwait(false); _restartOnShutdown = appHost.ShouldRestart; + _restoreFromBackup = appHost.RestoreBackupPath; } catch (Exception ex) { diff --git a/Jellyfin.Server/StartupOptions.cs b/Jellyfin.Server/StartupOptions.cs index 91ac827ca..4890ccbb2 100644 --- a/Jellyfin.Server/StartupOptions.cs +++ b/Jellyfin.Server/StartupOptions.cs @@ -73,6 +73,12 @@ namespace Jellyfin.Server [Option("nonetchange", Required = false, HelpText = "Indicates that the server should not detect network status change.")] public bool NoDetectNetworkChange { get; set; } + /// + /// Gets or sets the path to an jellyfin backup archive to restore the application to. + /// + [Option("restore-archive", Required = false, HelpText = "Path to a Jellyfin backup archive to restore from")] + public string? RestoreArchive { get; set; } + /// /// Gets the command line options as a dictionary that can be used in the .NET configuration system. /// diff --git a/MediaBrowser.Common/Configuration/IApplicationPaths.cs b/MediaBrowser.Common/Configuration/IApplicationPaths.cs index fa0d8247b..6d1a72b04 100644 --- a/MediaBrowser.Common/Configuration/IApplicationPaths.cs +++ b/MediaBrowser.Common/Configuration/IApplicationPaths.cs @@ -91,6 +91,12 @@ namespace MediaBrowser.Common.Configuration /// The trickplay path. string TrickplayPath { get; } + /// + /// Gets the path used for storing backup archives. + /// + /// The backup path. + string BackupPath { get; } + /// /// Checks and creates all known base paths. /// diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index e9c4d9e19..b76141db0 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -38,6 +38,11 @@ namespace MediaBrowser.Controller /// The name of the friendly. string FriendlyName { get; } + /// + /// Gets or sets the path to the backup archive used to restore upon restart. + /// + string RestoreBackupPath { get; set; } + /// /// Gets a URL specific for the request. /// diff --git a/MediaBrowser.Controller/SystemBackupService/BackupManifestDto.cs b/MediaBrowser.Controller/SystemBackupService/BackupManifestDto.cs new file mode 100644 index 000000000..b094ec275 --- /dev/null +++ b/MediaBrowser.Controller/SystemBackupService/BackupManifestDto.cs @@ -0,0 +1,34 @@ +using System; + +namespace MediaBrowser.Controller.SystemBackupService; + +/// +/// Manifest type for backups internal structure. +/// +public class BackupManifestDto +{ + /// + /// Gets or sets the jellyfin version this backup was created with. + /// + public required Version ServerVersion { get; set; } + + /// + /// Gets or sets the backup engine version this backup was created with. + /// + public required Version BackupEngineVersion { get; set; } + + /// + /// Gets or sets the date this backup was created with. + /// + public required DateTimeOffset DateCreated { get; set; } + + /// + /// Gets or sets the path to the backup on the system. + /// + public required string Path { get; set; } + + /// + /// Gets or sets the contents of the backup archive. + /// + public required BackupOptionsDto Options { get; set; } +} diff --git a/MediaBrowser.Controller/SystemBackupService/BackupOptionsDto.cs b/MediaBrowser.Controller/SystemBackupService/BackupOptionsDto.cs new file mode 100644 index 000000000..228839a1d --- /dev/null +++ b/MediaBrowser.Controller/SystemBackupService/BackupOptionsDto.cs @@ -0,0 +1,24 @@ +using System; + +namespace MediaBrowser.Controller.SystemBackupService; + +/// +/// Defines the optional contents of the backup archive. +/// +public class BackupOptionsDto +{ + /// + /// Gets or sets a value indicating whether the archive contains the Metadata contents. + /// + public bool Metadata { get; set; } + + /// + /// Gets or sets a value indicating whether the archive contains the Trickplay contents. + /// + public bool Trickplay { get; set; } + + /// + /// Gets or sets a value indicating whether the archive contains the Subtitle contents. + /// + public bool Subtitles { get; set; } +} diff --git a/MediaBrowser.Controller/SystemBackupService/BackupRestoreRequestDto.cs b/MediaBrowser.Controller/SystemBackupService/BackupRestoreRequestDto.cs new file mode 100644 index 000000000..263fa00c8 --- /dev/null +++ b/MediaBrowser.Controller/SystemBackupService/BackupRestoreRequestDto.cs @@ -0,0 +1,15 @@ +using System; +using MediaBrowser.Common.Configuration; + +namespace MediaBrowser.Controller.SystemBackupService; + +/// +/// Defines properties used to start a restore process. +/// +public class BackupRestoreRequestDto +{ + /// + /// Gets or Sets the name of the backup archive to restore from. Must be present in . + /// + public required string ArchiveFileName { get; set; } +} diff --git a/MediaBrowser.Controller/SystemBackupService/IBackupService.cs b/MediaBrowser.Controller/SystemBackupService/IBackupService.cs new file mode 100644 index 000000000..0c586d811 --- /dev/null +++ b/MediaBrowser.Controller/SystemBackupService/IBackupService.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using MediaBrowser.Controller.SystemBackupService; + +namespace Jellyfin.Server.Implementations.SystemBackupService; + +/// +/// Defines an interface to restore and backup the jellyfin system. +/// +public interface IBackupService +{ + /// + /// Creates a new Backup zip file containing the current state of the application. + /// + /// The backup options. + /// A task. + Task CreateBackupAsync(BackupOptionsDto backupOptions); + + /// + /// Gets a list of backups that are available to be restored from. + /// + /// A list of backup paths. + Task EnumerateBackups(); + + /// + /// Gets a single backup manifest if the path defines a valid Jellyfin backup archive. + /// + /// The path to be loaded. + /// The containing backup manifest or null if not existing or compatiable. + Task GetBackupManifest(string archivePath); + + /// + /// Restores an backup zip file created by jellyfin. + /// + /// Path to the archive. + /// A Task. + /// Thrown when an invalid or missing file is specified. + /// Thrown when attempt to load an unsupported backup is made. + /// Thrown for errors during the restore. + Task RestoreBackupAsync(string archivePath); + + /// + /// Schedules a Restore and restarts the server. + /// + /// The path to the archive to restore from. + void ScheduleRestoreAndRestartServer(string archivePath); +} diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/TrickplayInfo.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/TrickplayInfo.cs index 06b290e4f..39b449553 100644 --- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/TrickplayInfo.cs +++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/TrickplayInfo.cs @@ -14,7 +14,6 @@ public class TrickplayInfo /// /// Required. /// - [JsonIgnore] public Guid ItemId { get; set; } /// diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/User.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/User.cs index 4da7074ec..6c81fa729 100644 --- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/User.cs +++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/User.cs @@ -61,7 +61,6 @@ namespace Jellyfin.Database.Implementations.Entities /// /// Identity, Indexed, Required. /// - [JsonIgnore] public Guid Id { get; set; } /// diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/IJellyfinDatabaseProvider.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/IJellyfinDatabaseProvider.cs index 34ac7dc83..b0dc98469 100644 --- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/IJellyfinDatabaseProvider.cs +++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/IJellyfinDatabaseProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; @@ -62,4 +63,12 @@ public interface IJellyfinDatabaseProvider /// A cancellation token. /// A representing the result of the asynchronous operation. Task RestoreBackupFast(string key, CancellationToken cancellationToken); + + /// + /// Removes all contents from the database. + /// + /// The Database context. + /// The names of the tables to purge or null for all tables to be purged. + /// A Task. + Task PurgeDatabase(JellyfinDbContext dbContext, IEnumerable? tableNames); } diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/SqliteDatabaseProvider.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/SqliteDatabaseProvider.cs index 156d9618e..519584003 100644 --- a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/SqliteDatabaseProvider.cs +++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/SqliteDatabaseProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.IO; using System.Threading; @@ -82,7 +83,7 @@ public sealed class SqliteDatabaseProvider : IJellyfinDatabaseProvider } // Run before disposing the application - var context = await DbContextFactory!.CreateDbContextAsync(cancellationToken).ConfigureAwait(false); + var context = await DbContextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false); await using (context.ConfigureAwait(false)) { await context.Database.ExecuteSqlRawAsync("PRAGMA optimize", cancellationToken).ConfigureAwait(false); @@ -127,4 +128,25 @@ public sealed class SqliteDatabaseProvider : IJellyfinDatabaseProvider File.Copy(backupFile, path, true); return Task.CompletedTask; } + + /// + public async Task PurgeDatabase(JellyfinDbContext dbContext, IEnumerable? tableNames) + { + ArgumentNullException.ThrowIfNull(tableNames); + + var deleteQueries = new List(); + foreach (var tableName in tableNames) + { + deleteQueries.Add($"DELETE FROM \"{tableName}\";"); + } + + var deleteAllQuery = + $""" + PRAGMA foreign_keys = OFF; + {string.Join('\n', deleteQueries)} + PRAGMA foreign_keys = ON; + """; + + await dbContext.Database.ExecuteSqlRawAsync(deleteAllQuery).ConfigureAwait(false); + } } diff --git a/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs index dd84c1a18..8cb3cde2b 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs +++ b/tests/Jellyfin.Api.Tests/Controllers/SystemControllerTests.cs @@ -1,4 +1,5 @@ using Jellyfin.Api.Controllers; +using Jellyfin.Server.Implementations.SystemBackupService; using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Model.IO; -- cgit v1.2.3