Skip to content

The Free Software Media System - Server Backend & API

19.2 KB
Raw Blame
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Api.Models.LibraryStructureDto;
using Jellyfin.Data;
using Jellyfin.Data.Enums;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Database.Implementations.Enums;
using MediaBrowser.Common.Api;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Jellyfin.Api.Controllers;

/// <summary>
/// The library structure controller.
/// </summary>
[Route("Library/VirtualFolders")]
[Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
public class LibraryStructureController : BaseJellyfinApiController
{
    private readonly IServerApplicationPaths _appPaths;
    private readonly ILibraryManager _libraryManager;
    private readonly ILibraryMonitor _libraryMonitor;
    private readonly IDirectoryService _directoryService;
    private readonly IUserManager _userManager;

    /// <summary>
    /// Initializes a new instance of the <see cref="LibraryStructureController"/> class.
    /// </summary>
    /// <param name="serverConfigurationManager">Instance of <see cref="IServerConfigurationManager"/> interface.</param>
    /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
    /// <param name="libraryMonitor">Instance of <see cref="ILibraryMonitor"/> interface.</param>
    /// <param name="directoryService">Instance of <see cref="IDirectoryService"/> interface.</param>
    /// <param name="userManager">Instance of <see cref="IUserManager"/> interface.</param>
    public LibraryStructureController(
        IServerConfigurationManager serverConfigurationManager,
        ILibraryManager libraryManager,
        ILibraryMonitor libraryMonitor,
        IDirectoryService directoryService,
        IUserManager userManager)
    {
        _appPaths = serverConfigurationManager.ApplicationPaths;
        _libraryManager = libraryManager;
        _libraryMonitor = libraryMonitor;
        _directoryService = directoryService;
        _userManager = userManager;
    }

    /// <summary>
    /// Gets all virtual folders.
    /// </summary>
    /// <response code="200">Virtual folders retrieved.</response>
    /// <returns>An <see cref="IEnumerable{VirtualFolderInfo}"/> with the virtual folders.</returns>
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult<IEnumerable<VirtualFolderInfo>> GetVirtualFolders()
    {
        return _libraryManager.GetVirtualFolders(true);
    }

    /// <summary>
    /// Adds a virtual folder.
    /// </summary>
    /// <param name="name">The name of the virtual folder.</param>
    /// <param name="collectionType">The type of the collection.</param>
    /// <param name="paths">The paths of the virtual folder.</param>
    /// <param name="libraryOptionsDto">The library options.</param>
    /// <param name="refreshLibrary">Whether to refresh the library.</param>
    /// <response code="204">Folder added.</response>
    /// <returns>A <see cref="NoContentResult"/>.</returns>
    [HttpPost]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task<ActionResult> AddVirtualFolder(
        [FromQuery]
        [RegularExpression(@"^(?:\S(?:.*\S)?)$", ErrorMessage = "Library name cannot be empty or have leading/trailing spaces.")]
        string name,
        [FromQuery] CollectionTypeOptions? collectionType,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] string[] paths,
        [FromBody] AddVirtualFolderDto? libraryOptionsDto,
        [FromQuery] bool refreshLibrary = false)
    {
        var libraryOptions = libraryOptionsDto?.LibraryOptions ?? new LibraryOptions();

        if (paths is not null && paths.Length > 0)
        {
            libraryOptions.PathInfos = Array.ConvertAll(paths, i => new MediaPathInfo(i));
        }

        await _libraryManager.AddVirtualFolder(name, collectionType, libraryOptions, refreshLibrary).ConfigureAwait(false);

        return NoContent();
    }

    /// <summary>
    /// Removes a virtual folder.
    /// </summary>
    /// <param name="name">The name of the folder.</param>
    /// <param name="refreshLibrary">Whether to refresh the library.</param>
    /// <response code="204">Folder removed.</response>
    /// <response code="404">Folder not found.</response>
    /// <returns>A <see cref="NoContentResult"/>.</returns>
    [HttpDelete]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task<ActionResult> RemoveVirtualFolder(
        [FromQuery] string name,
        [FromQuery] bool refreshLibrary = false)
    {
        // TODO: refactor! this relies on an FileNotFound exception to return NotFound when attempting to remove a library that does not exist.
        await _libraryManager.RemoveVirtualFolder(name, refreshLibrary).ConfigureAwait(false);

        return NoContent();
    }

    /// <summary>
    /// Renames a virtual folder.
    /// </summary>
    /// <param name="name">The name of the virtual folder.</param>
    /// <param name="newName">The new name.</param>
    /// <param name="refreshLibrary">Whether to refresh the library.</param>
    /// <response code="204">Folder renamed.</response>
    /// <response code="400">The new name is not a valid library name.</response>
    /// <response code="404">Library doesn't exist.</response>
    /// <response code="409">Library already exists.</response>
    /// <returns>A <see cref="NoContentResult"/> on success, a <see cref="BadRequestResult"/> if the new name is invalid, a <see cref="NotFoundResult"/> if the library doesn't exist, a <see cref="ConflictResult"/> if the new name is already taken.</returns>
    /// <exception cref="ArgumentNullException">The new name may not be null.</exception>
    [HttpPost("Name")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    public async Task<ActionResult> RenameVirtualFolder(
        [FromQuery] string? name,
        [FromQuery] string? newName,
        [FromQuery] bool refreshLibrary = false)
    {
        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentNullException(nameof(name));
        }

        if (string.IsNullOrWhiteSpace(newName))
        {
            throw new ArgumentNullException(nameof(newName));
        }

        var rootFolderPath = _appPaths.DefaultUserViewsPath;

        // Both names are caller supplied, so they have to be confined to the libraries root.
        var newPath = FileSystemHelper.GetChildPath(rootFolderPath, newName);
        if (newPath is null)
        {
            return BadRequest("The new name is not a valid library name.");
        }

        var currentPath = FileSystemHelper.GetChildPath(rootFolderPath, name);
        if (currentPath is null || !Directory.Exists(currentPath))
        {
            return NotFound("The media collection does not exist.");
        }

        if (!string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(newPath))
        {
            return Conflict($"The media library already exists at {newPath}.");
        }

        var oldLibrary = FindLibrary(currentPath);
        // Use the stored ID when possible. The case sensitivity setting may have changed since the library was created.
        var oldLibraryId = oldLibrary?.Id ?? _libraryManager.GetNewItemId(currentPath, typeof(CollectionFolder));
        var oldLibraryName = oldLibrary?.Name ?? Path.GetFileName(currentPath);
        var newLibraryId = _libraryManager.GetNewItemId(newPath, typeof(CollectionFolder));

        _libraryMonitor.Stop();

        try
        {
            // Changing capitalization. Handle windows case insensitivity
            if (string.Equals(currentPath, newPath, StringComparison.OrdinalIgnoreCase))
            {
                var tempPath = Path.Combine(
                    rootFolderPath,
                    Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
                _directoryService.Move(currentPath, tempPath);
                currentPath = tempPath;
            }

            _directoryService.Move(currentPath, newPath);

            await ReplaceLibraryIdInUserPreferencesAsync(
                oldLibraryId,
                newLibraryId,
                oldLibraryName,
                Path.GetFileName(newPath),
                oldLibrary?.CollectionType).ConfigureAwait(false);
        }
        finally
        {
            CollectionFolder.OnCollectionFolderChange();

            _ = Task.Run(() => RefreshAfterRenameAsync(newPath, refreshLibrary));
        }

        return NoContent();
    }

    private async Task RefreshAfterRenameAsync(string newPath, bool refreshLibrary)
    {
        // No need to start if scanning the library because it will handle it
        if (refreshLibrary)
        {
            await _libraryManager.ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false);
            var newLib = _libraryManager.GetUserRootFolder().Children.FirstOrDefault(f => f.Path.Equals(newPath, StringComparison.OrdinalIgnoreCase));
            if (newLib is CollectionFolder folder)
            {
                _libraryManager.ClearIgnoreRuleCache();
                foreach (var child in folder.GetPhysicalFolders())
                {
                    await child.RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
                    await child.ValidateChildren(new Progress<double>(), CancellationToken.None).ConfigureAwait(false);
                }
            }
            else
            {
                _libraryManager.ClearIgnoreRuleCache();
                // We don't know if this one can be validated individually, trigger a new validation
                _libraryManager.QueueLibraryScan();
            }

            _libraryManager.ClearIgnoreRuleCache();
        }
        else
        {
            // Need to add a delay here or directory watchers may still pick up the changes
            // Have to block here to allow exceptions to bubble
            await Task.Delay(1000).ConfigureAwait(false);
            _libraryMonitor.Start();
        }
    }

    private CollectionFolder? FindLibrary(string path)
        => _libraryManager.GetUserRootFolder().Children
            .OfType<CollectionFolder>()
            .FirstOrDefault(f => string.Equals(f.Path, path, StringComparison.OrdinalIgnoreCase));

    private async Task ReplaceLibraryIdInUserPreferencesAsync(
        Guid oldId,
        Guid newId,
        string oldName,
        string newName,
        CollectionType? viewType)
    {
        var shadowView = (
            Old: _libraryManager.GetShadowViewId(oldName, oldId, viewType),
            New: _libraryManager.GetShadowViewId(newName, newId, viewType));

        if (oldId.Equals(newId) && shadowView.Old.Equals(shadowView.New))
        {
            return;
        }

        PreferenceKind[] libraryPreferences =
        [
            PreferenceKind.EnabledFolders,
            PreferenceKind.BlockedMediaFolders,
            PreferenceKind.EnableContentDeletionFromFolders,
            PreferenceKind.LatestItemExcludes,
            PreferenceKind.MyMediaExcludes,
            PreferenceKind.GroupedFolders,
            PreferenceKind.OrderedViews
        ];

        // These lists hold what the "My Media" row shows, which includes the views built from a library.
        PreferenceKind[] viewPreferences = [PreferenceKind.MyMediaExcludes, PreferenceKind.OrderedViews];

        foreach (var user in _userManager.GetUsers())
        {
            var libraryMap = new Dictionary<Guid, Guid> { [oldId] = newId };
            var viewMap = new Dictionary<Guid, Guid>(libraryMap)
            {
                [shadowView.Old] = shadowView.New,
                [_libraryManager.GetNamedViewId(user, oldId, viewType)] = _libraryManager.GetNamedViewId(user, newId, viewType)
            };

            var changed = false;

            foreach (var kind in libraryPreferences)
            {
                changed |= ReplaceIds(user, kind, viewPreferences.Contains(kind) ? viewMap : libraryMap);
            }

            if (changed)
            {
                await _userManager.UpdateUserAsync(user).ConfigureAwait(false);
            }
        }
    }

    private static bool ReplaceIds(User user, PreferenceKind kind, Dictionary<Guid, Guid> map)
    {
        var values = user.GetPreference(kind);
        var rewritten = new List<string>(values.Length);
        var seen = new HashSet<Guid>();
        var touched = false;

        foreach (var value in values)
        {
            // Clients write these in both the dashed and the plain form, so compare them parsed.
            if (!Guid.TryParse(value, out var parsed))
            {
                rewritten.Add(value);
                continue;
            }

            var isReplaced = map.TryGetValue(parsed, out var replacement) && !replacement.Equals(parsed);
            if (isReplaced)
            {
                parsed = replacement;
                touched = true;
            }

            if (!seen.Add(parsed))
            {
                touched = true;
                continue;
            }

            var format = value.Contains('-', StringComparison.Ordinal) ? "D" : "N";
            rewritten.Add(isReplaced ? parsed.ToString(format, CultureInfo.InvariantCulture) : value);
        }

        if (touched)
        {
            user.SetPreference(kind, rewritten.ToArray());
        }

        return touched;
    }

    /// <summary>
    /// Add a media path to a library.
    /// </summary>
    /// <param name="mediaPathDto">The media path dto.</param>
    /// <param name="refreshLibrary">Whether to refresh the library.</param>
    /// <returns>A <see cref="NoContentResult"/>.</returns>
    /// <response code="204">Media path added.</response>
    /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
    [HttpPost("Paths")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public ActionResult AddMediaPath(
        [FromBody, Required] MediaPathDto mediaPathDto,
        [FromQuery] bool refreshLibrary = false)
    {
        _libraryMonitor.Stop();

        try
        {
            var mediaPath = mediaPathDto.PathInfo ?? new MediaPathInfo(mediaPathDto.Path ?? throw new ArgumentException("PathInfo and Path can't both be null."));

            _libraryManager.AddMediaPath(mediaPathDto.Name, mediaPath);
        }
        finally
        {
            Task.Run(async () =>
            {
                // No need to start if scanning the library because it will handle it
                if (refreshLibrary)
                {
                    _libraryManager.QueueLibraryScan();
                }
                else
                {
                    // Need to add a delay here or directory watchers may still pick up the changes
                    // Have to block here to allow exceptions to bubble
                    await Task.Delay(1000).ConfigureAwait(false);
                    _libraryMonitor.Start();
                }
            });
        }

        return NoContent();
    }

    /// <summary>
    /// Updates a media path.
    /// </summary>
    /// <param name="mediaPathRequestDto">The name of the library and path infos.</param>
    /// <returns>A <see cref="NoContentResult"/>.</returns>
    /// <response code="204">Media path updated.</response>
    /// <exception cref="ArgumentNullException">The name of the library may not be empty.</exception>
    [HttpPost("Paths/Update")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public ActionResult UpdateMediaPath([FromBody, Required] UpdateMediaPathRequestDto mediaPathRequestDto)
    {
        if (string.IsNullOrWhiteSpace(mediaPathRequestDto.Name))
        {
            throw new ArgumentNullException(nameof(mediaPathRequestDto), "Name must not be null or empty");
        }

        _libraryManager.UpdateMediaPath(mediaPathRequestDto.Name, mediaPathRequestDto.PathInfo);
        return NoContent();
    }

    /// <summary>
    /// Remove a media path.
    /// </summary>
    /// <param name="name">The name of the library.</param>
    /// <param name="path">The path to remove.</param>
    /// <param name="refreshLibrary">Whether to refresh the library.</param>
    /// <returns>A <see cref="NoContentResult"/>.</returns>
    /// <response code="204">Media path removed.</response>
    /// <exception cref="ArgumentException">The name of the library and path may not be empty.</exception>
    [HttpDelete("Paths")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public ActionResult RemoveMediaPath(
        [FromQuery] string name,
        [FromQuery] string path,
        [FromQuery] bool refreshLibrary = false)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(name);
        ArgumentException.ThrowIfNullOrWhiteSpace(path);

        _libraryMonitor.Stop();

        try
        {
            _libraryManager.RemoveMediaPath(name, path);
        }
        finally
        {
            Task.Run(async () =>
            {
                // No need to start if scanning the library because it will handle it
                if (refreshLibrary)
                {
                    _libraryManager.QueueLibraryScan();
                }
                else
                {
                    // Need to add a delay here or directory watchers may still pick up the changes
                    // Have to block here to allow exceptions to bubble
                    await Task.Delay(1000).ConfigureAwait(false);
                    _libraryMonitor.Start();
                }
            });
        }

        return NoContent();
    }

    /// <summary>
    /// Update library options.
    /// </summary>
    /// <param name="request">The library name and options.</param>
    /// <response code="204">Library updated.</response>
    /// <response code="404">Item not found.</response>
    /// <returns>A <see cref="NoContentResult"/>.</returns>
    [HttpPost("LibraryOptions")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public ActionResult UpdateLibraryOptions(
        [FromBody] UpdateLibraryOptionsDto request)
    {
        var item = _libraryManager.GetItemById<CollectionFolder>(request.Id);
        if (item is null)
        {
            return NotFound();
        }

        LibraryOptions options = item.GetLibraryOptions();
        foreach (var mediaPath in request.LibraryOptions!.PathInfos)
        {
            if (options.PathInfos.Any(i => i.Path == mediaPath.Path))
            {
                continue;
            }

            _libraryManager.CreateShortcut(item.Path, mediaPath);
        }

        item.UpdateLibraryOptions(request.LibraryOptions);
        return NoContent();
    }
}