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;
///
/// The library structure controller.
///
[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;
///
/// Initializes a new instance of the class.
///
/// Instance of interface.
/// Instance of interface.
/// Instance of interface.
/// Instance of interface.
/// Instance of interface.
public LibraryStructureController(
IServerConfigurationManager serverConfigurationManager,
ILibraryManager libraryManager,
ILibraryMonitor libraryMonitor,
IDirectoryService directoryService,
IUserManager userManager)
{
_appPaths = serverConfigurationManager.ApplicationPaths;
_libraryManager = libraryManager;
_libraryMonitor = libraryMonitor;
_directoryService = directoryService;
_userManager = userManager;
}
///
/// Gets all virtual folders.
///
/// Virtual folders retrieved.
/// An with the virtual folders.
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult> GetVirtualFolders()
{
return _libraryManager.GetVirtualFolders(true);
}
///
/// Adds a virtual folder.
///
/// The name of the virtual folder.
/// The type of the collection.
/// The paths of the virtual folder.
/// The library options.
/// Whether to refresh the library.
/// Folder added.
/// A .
[HttpPost]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task 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();
}
///
/// Removes a virtual folder.
///
/// The name of the folder.
/// Whether to refresh the library.
/// Folder removed.
/// Folder not found.
/// A .
[HttpDelete]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task 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();
}
///
/// Renames a virtual folder.
///
/// The name of the virtual folder.
/// The new name.
/// Whether to refresh the library.
/// Folder renamed.
/// The new name is not a valid library name.
/// Library doesn't exist.
/// Library already exists.
/// A on success, a if the new name is invalid, a if the library doesn't exist, a if the new name is already taken.
/// The new name may not be null.
[HttpPost("Name")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task 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(), 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()
.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 { [oldId] = newId };
var viewMap = new Dictionary(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 map)
{
var values = user.GetPreference(kind);
var rewritten = new List(values.Length);
var seen = new HashSet();
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;
}
///
/// Add a media path to a library.
///
/// The media path dto.
/// Whether to refresh the library.
/// A .
/// Media path added.
/// The name of the library may not be empty.
[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();
}
///
/// Updates a media path.
///
/// The name of the library and path infos.
/// A .
/// Media path updated.
/// The name of the library may not be empty.
[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();
}
///
/// Remove a media path.
///
/// The name of the library.
/// The path to remove.
/// Whether to refresh the library.
/// A .
/// Media path removed.
/// The name of the library and path may not be empty.
[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();
}
///
/// Update library options.
///
/// The library name and options.
/// Library updated.
/// Item not found.
/// A .
[HttpPost("LibraryOptions")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult UpdateLibraryOptions(
[FromBody] UpdateLibraryOptionsDto request)
{
var item = _libraryManager.GetItemById(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();
}
}