Переглянути джерело

Merge pull request #2984 from crobibero/api-library

Move Library Service to Jellyfin.API
Cody Robibero 5 роки тому
батько
коміт
7c1020cfc1

+ 10 - 1
Jellyfin.Api/Auth/BaseAuthorizationHandler.cs

@@ -42,11 +42,13 @@ namespace Jellyfin.Api.Auth
         /// <param name="claimsPrincipal">Request claims.</param>
         /// <param name="ignoreSchedule">Whether to ignore parental control.</param>
         /// <param name="localAccessOnly">Whether access is to be allowed locally only.</param>
+        /// <param name="requiredDownloadPermission">Whether validation requires download permission.</param>
         /// <returns>Validated claim status.</returns>
         protected bool ValidateClaims(
             ClaimsPrincipal claimsPrincipal,
             bool ignoreSchedule = false,
-            bool localAccessOnly = false)
+            bool localAccessOnly = false,
+            bool requiredDownloadPermission = false)
         {
             // Ensure claim has userId.
             var userId = ClaimHelpers.GetUserId(claimsPrincipal);
@@ -89,6 +91,13 @@ namespace Jellyfin.Api.Auth
                 return false;
             }
 
+            // User attempting to download without permission.
+            if (requiredDownloadPermission
+                && !user.HasPermission(PermissionKind.EnableContentDownloading))
+            {
+                return false;
+            }
+
             return true;
         }
 

+ 45 - 0
Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs

@@ -0,0 +1,45 @@
+using System.Threading.Tasks;
+using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Library;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+
+namespace Jellyfin.Api.Auth.DownloadPolicy
+{
+    /// <summary>
+    /// Download authorization handler.
+    /// </summary>
+    public class DownloadHandler : BaseAuthorizationHandler<DownloadRequirement>
+    {
+        /// <summary>
+        /// Initializes a new instance of the <see cref="DownloadHandler"/> class.
+        /// </summary>
+        /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+        /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
+        /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
+        public DownloadHandler(
+            IUserManager userManager,
+            INetworkManager networkManager,
+            IHttpContextAccessor httpContextAccessor)
+            : base(userManager, networkManager, httpContextAccessor)
+        {
+        }
+
+        /// <inheritdoc />
+        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DownloadRequirement requirement)
+        {
+            var validated = ValidateClaims(context.User);
+            if (validated)
+            {
+                context.Succeed(requirement);
+            }
+            else
+            {
+                context.Fail();
+            }
+
+            return Task.CompletedTask;
+        }
+    }
+}

+ 11 - 0
Jellyfin.Api/Auth/DownloadPolicy/DownloadRequirement.cs

@@ -0,0 +1,11 @@
+using Microsoft.AspNetCore.Authorization;
+
+namespace Jellyfin.Api.Auth.DownloadPolicy
+{
+    /// <summary>
+    /// The download permission requirement.
+    /// </summary>
+    public class DownloadRequirement : IAuthorizationRequirement
+    {
+    }
+}

+ 5 - 0
Jellyfin.Api/Constants/Policies.cs

@@ -29,5 +29,10 @@ namespace Jellyfin.Api.Constants
         /// Policy name for escaping schedule controls.
         /// </summary>
         public const string IgnoreSchedule = "IgnoreSchedule";
+
+        /// <summary>
+        /// Policy name for requiring download permission.
+        /// </summary>
+        public const string Download = "Download";
     }
 }

+ 1049 - 0
Jellyfin.Api/Controllers/LibraryController.cs

@@ -0,0 +1,1049 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Api.Models.LibraryDtos;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Common.Progress;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Providers;
+using MediaBrowser.Model.Activity;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Globalization;
+using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.Logging;
+using Book = MediaBrowser.Controller.Entities.Book;
+using Movie = Jellyfin.Data.Entities.Movie;
+using MusicAlbum = Jellyfin.Data.Entities.MusicAlbum;
+
+namespace Jellyfin.Api.Controllers
+{
+    /// <summary>
+    /// Library Controller.
+    /// </summary>
+    public class LibraryController : BaseJellyfinApiController
+    {
+        private readonly IProviderManager _providerManager;
+        private readonly ILibraryManager _libraryManager;
+        private readonly IUserManager _userManager;
+        private readonly IDtoService _dtoService;
+        private readonly IAuthorizationContext _authContext;
+        private readonly IActivityManager _activityManager;
+        private readonly ILocalizationManager _localization;
+        private readonly ILibraryMonitor _libraryMonitor;
+        private readonly ILogger<LibraryController> _logger;
+        private readonly IServerConfigurationManager _serverConfigurationManager;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="LibraryController"/> class.
+        /// </summary>
+        /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
+        /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
+        /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
+        /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
+        /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
+        /// <param name="activityManager">Instance of the <see cref="IActivityManager"/> interface.</param>
+        /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
+        /// <param name="libraryMonitor">Instance of the <see cref="ILibraryMonitor"/> interface.</param>
+        /// <param name="logger">Instance of the <see cref="ILogger{LibraryController}"/> interface.</param>
+        /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+        public LibraryController(
+            IProviderManager providerManager,
+            ILibraryManager libraryManager,
+            IUserManager userManager,
+            IDtoService dtoService,
+            IAuthorizationContext authContext,
+            IActivityManager activityManager,
+            ILocalizationManager localization,
+            ILibraryMonitor libraryMonitor,
+            ILogger<LibraryController> logger,
+            IServerConfigurationManager serverConfigurationManager)
+        {
+            _providerManager = providerManager;
+            _libraryManager = libraryManager;
+            _userManager = userManager;
+            _dtoService = dtoService;
+            _authContext = authContext;
+            _activityManager = activityManager;
+            _localization = localization;
+            _libraryMonitor = libraryMonitor;
+            _logger = logger;
+            _serverConfigurationManager = serverConfigurationManager;
+        }
+
+        /// <summary>
+        /// Get the original file of an item.
+        /// </summary>
+        /// <param name="itemId">The item id.</param>
+        /// <response code="200">File stream returned.</response>
+        /// <response code="404">Item not found.</response>
+        /// <returns>A <see cref="FileStreamResult"/> with the original file.</returns>
+        [HttpGet("/Items/{itemId}/File")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        [ProducesResponseType(StatusCodes.Status404NotFound)]
+        public ActionResult GetFile([FromRoute] Guid itemId)
+        {
+            var item = _libraryManager.GetItemById(itemId);
+            if (item == null)
+            {
+                return NotFound();
+            }
+
+            using var fileStream = new FileStream(item.Path, FileMode.Open, FileAccess.Read);
+            return File(fileStream, MimeTypes.GetMimeType(item.Path));
+        }
+
+        /// <summary>
+        /// Gets critic review for an item.
+        /// </summary>
+        /// <param name="itemId">The item id.</param>
+        /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
+        /// <param name="limit">Optional. The maximum number of records to return.</param>
+        /// <response code="200">Critic reviews returned.</response>
+        /// <returns>The list of critic reviews.</returns>
+        [HttpGet("/Items/{itemId}/CriticReviews")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [Obsolete("This endpoint is obsolete.")]
+        [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Imported from ServiceStack")]
+        [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "startIndex", Justification = "Imported from ServiceStack")]
+        [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "limit", Justification = "Imported from ServiceStack")]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        public ActionResult<QueryResult<BaseItemDto>> GetCriticReviews(
+            [FromRoute] Guid itemId,
+            [FromQuery] int? startIndex,
+            [FromQuery] int? limit)
+        {
+            return new QueryResult<BaseItemDto>();
+        }
+
+        /// <summary>
+        /// Get theme songs for an item.
+        /// </summary>
+        /// <param name="itemId">The item id.</param>
+        /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+        /// <param name="inheritFromParent">Optional. Determines whether or not parent items should be searched for theme media.</param>
+        /// <response code="200">Theme songs returned.</response>
+        /// <response code="404">Item not found.</response>
+        /// <returns>The item theme songs.</returns>
+        [HttpGet("/Items/{itemId}/ThemeSongs")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        [ProducesResponseType(StatusCodes.Status404NotFound)]
+        public ActionResult<ThemeMediaResult> GetThemeSongs(
+            [FromRoute] Guid itemId,
+            [FromQuery] Guid userId,
+            [FromQuery] bool inheritFromParent)
+        {
+            var user = !userId.Equals(Guid.Empty)
+                ? _userManager.GetUserById(userId)
+                : null;
+
+            var item = itemId.Equals(Guid.Empty)
+                ? (!userId.Equals(Guid.Empty)
+                    ? _libraryManager.GetUserRootFolder()
+                    : _libraryManager.RootFolder)
+                : _libraryManager.GetItemById(itemId);
+
+            if (item == null)
+            {
+                return NotFound("Item not found.");
+            }
+
+            IEnumerable<BaseItem> themeItems;
+
+            while (true)
+            {
+                themeItems = item.GetThemeSongs();
+
+                if (themeItems.Any() || !inheritFromParent)
+                {
+                    break;
+                }
+
+                var parent = item.GetParent();
+                if (parent == null)
+                {
+                    break;
+                }
+
+                item = parent;
+            }
+
+            var dtoOptions = new DtoOptions().AddClientFields(Request);
+            var items = themeItems
+                .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item))
+                .ToArray();
+
+            return new ThemeMediaResult
+            {
+                Items = items,
+                TotalRecordCount = items.Length,
+                OwnerId = item.Id
+            };
+        }
+
+        /// <summary>
+        /// Get theme videos for an item.
+        /// </summary>
+        /// <param name="itemId">The item id.</param>
+        /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+        /// <param name="inheritFromParent">Optional. Determines whether or not parent items should be searched for theme media.</param>
+        /// <response code="200">Theme videos returned.</response>
+        /// <response code="404">Item not found.</response>
+        /// <returns>The item theme videos.</returns>
+        [HttpGet("/Items/{itemId}/ThemeVideos")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        [ProducesResponseType(StatusCodes.Status404NotFound)]
+        public ActionResult<ThemeMediaResult> GetThemeVideos(
+            [FromRoute] Guid itemId,
+            [FromQuery] Guid userId,
+            [FromQuery] bool inheritFromParent)
+        {
+            var user = !userId.Equals(Guid.Empty)
+                ? _userManager.GetUserById(userId)
+                : null;
+
+            var item = itemId.Equals(Guid.Empty)
+                ? (!userId.Equals(Guid.Empty)
+                    ? _libraryManager.GetUserRootFolder()
+                    : _libraryManager.RootFolder)
+                : _libraryManager.GetItemById(itemId);
+
+            if (item == null)
+            {
+                return NotFound("Item not found.");
+            }
+
+            IEnumerable<BaseItem> themeItems;
+
+            while (true)
+            {
+                themeItems = item.GetThemeVideos();
+
+                if (themeItems.Any() || !inheritFromParent)
+                {
+                    break;
+                }
+
+                var parent = item.GetParent();
+                if (parent == null)
+                {
+                    break;
+                }
+
+                item = parent;
+            }
+
+            var dtoOptions = new DtoOptions().AddClientFields(Request);
+            var items = themeItems
+                .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item))
+                .ToArray();
+
+            return new ThemeMediaResult
+            {
+                Items = items,
+                TotalRecordCount = items.Length,
+                OwnerId = item.Id
+            };
+        }
+
+        /// <summary>
+        /// Get theme songs and videos for an item.
+        /// </summary>
+        /// <param name="itemId">The item id.</param>
+        /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+        /// <param name="inheritFromParent">Optional. Determines whether or not parent items should be searched for theme media.</param>
+        /// <response code="200">Theme songs and videos returned.</response>
+        /// <response code="404">Item not found.</response>
+        /// <returns>The item theme videos.</returns>
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        public ActionResult<AllThemeMediaResult> GetThemeMedia(
+            [FromRoute] Guid itemId,
+            [FromQuery] Guid userId,
+            [FromQuery] bool inheritFromParent)
+        {
+            var themeSongs = GetThemeSongs(
+                itemId,
+                userId,
+                inheritFromParent);
+
+            var themeVideos = GetThemeVideos(
+                itemId,
+                userId,
+                inheritFromParent);
+
+            return new AllThemeMediaResult
+            {
+                ThemeSongsResult = themeSongs?.Value,
+                ThemeVideosResult = themeVideos?.Value,
+                SoundtrackSongsResult = new ThemeMediaResult()
+            };
+        }
+
+        /// <summary>
+        /// Starts a library scan.
+        /// </summary>
+        /// <response code="204">Library scan started.</response>
+        /// <returns>A <see cref="NoContentResult"/>.</returns>
+        [HttpGet("/Library/Refresh")]
+        [Authorize(Policy = Policies.RequiresElevation)]
+        [ProducesResponseType(StatusCodes.Status204NoContent)]
+        public async Task<ActionResult> RefreshLibrary()
+        {
+            try
+            {
+                await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
+            }
+            catch (Exception ex)
+            {
+                 _logger.LogError(ex, "Error refreshing library");
+            }
+
+            return NoContent();
+        }
+
+        /// <summary>
+        /// Deletes an item from the library and filesystem.
+        /// </summary>
+        /// <param name="itemId">The item id.</param>
+        /// <response code="204">Item deleted.</response>
+        /// <response code="401">Unauthorized access.</response>
+        /// <returns>A <see cref="NoContentResult"/>.</returns>
+        [HttpDelete("/Items/{itemId}")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status204NoContent)]
+        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+        public ActionResult DeleteItem(Guid itemId)
+        {
+            var item = _libraryManager.GetItemById(itemId);
+            var auth = _authContext.GetAuthorizationInfo(Request);
+            var user = auth.User;
+
+            if (!item.CanDelete(user))
+            {
+                return Unauthorized("Unauthorized access");
+            }
+
+            _libraryManager.DeleteItem(
+                item,
+                new DeleteOptions { DeleteFileLocation = true },
+                true);
+
+            return NoContent();
+        }
+
+        /// <summary>
+        /// Deletes items from the library and filesystem.
+        /// </summary>
+        /// <param name="ids">The item ids.</param>
+        /// <response code="204">Items deleted.</response>
+        /// <response code="401">Unauthorized access.</response>
+        /// <returns>A <see cref="NoContentResult"/>.</returns>
+        [HttpDelete("/Items")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status204NoContent)]
+        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
+        public ActionResult DeleteItems([FromQuery] string ids)
+        {
+            var itemIds = string.IsNullOrWhiteSpace(ids)
+                ? Array.Empty<string>()
+                : RequestHelpers.Split(ids, ',', true);
+
+            foreach (var i in itemIds)
+            {
+                var item = _libraryManager.GetItemById(i);
+                var auth = _authContext.GetAuthorizationInfo(Request);
+                var user = auth.User;
+
+                if (!item.CanDelete(user))
+                {
+                    if (ids.Length > 1)
+                    {
+                        return Unauthorized("Unauthorized access");
+                    }
+
+                    continue;
+                }
+
+                _libraryManager.DeleteItem(
+                    item,
+                    new DeleteOptions { DeleteFileLocation = true },
+                    true);
+            }
+
+            return NoContent();
+        }
+
+        /// <summary>
+        /// Get item counts.
+        /// </summary>
+        /// <param name="userId">Optional. Get counts from a specific user's library.</param>
+        /// <param name="isFavorite">Optional. Get counts of favorite items.</param>
+        /// <response code="200">Item counts returned.</response>
+        /// <returns>Item counts.</returns>
+        [HttpGet("/Items/Counts")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        public ActionResult<ItemCounts> GetItemCounts(
+            [FromQuery] Guid userId,
+            [FromQuery] bool? isFavorite)
+        {
+            var user = userId.Equals(Guid.Empty)
+                ? null
+                : _userManager.GetUserById(userId);
+
+            var counts = new ItemCounts
+            {
+                AlbumCount = GetCount(typeof(MusicAlbum), user, isFavorite),
+                EpisodeCount = GetCount(typeof(Episode), user, isFavorite),
+                MovieCount = GetCount(typeof(Movie), user, isFavorite),
+                SeriesCount = GetCount(typeof(Series), user, isFavorite),
+                SongCount = GetCount(typeof(Audio), user, isFavorite),
+                MusicVideoCount = GetCount(typeof(MusicVideo), user, isFavorite),
+                BoxSetCount = GetCount(typeof(BoxSet), user, isFavorite),
+                BookCount = GetCount(typeof(Book), user, isFavorite)
+            };
+
+            return counts;
+        }
+
+        /// <summary>
+        /// Gets all parents of an item.
+        /// </summary>
+        /// <param name="itemId">The item id.</param>
+        /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+        /// <response code="200">Item parents returned.</response>
+        /// <response code="404">Item not found.</response>
+        /// <returns>Item parents.</returns>
+        [HttpGet("/Items/{itemId}/Ancestors")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        [ProducesResponseType(StatusCodes.Status404NotFound)]
+        public ActionResult<IEnumerable<BaseItemDto>> GetAncestors([FromRoute] Guid itemId, [FromQuery] Guid userId)
+        {
+            var item = _libraryManager.GetItemById(itemId);
+
+            if (item == null)
+            {
+                return NotFound("Item not found");
+            }
+
+            var baseItemDtos = new List<BaseItemDto>();
+
+            var user = !userId.Equals(Guid.Empty)
+                ? _userManager.GetUserById(userId)
+                : null;
+
+            var dtoOptions = new DtoOptions().AddClientFields(Request);
+            BaseItem parent = item.GetParent();
+
+            while (parent != null)
+            {
+                if (user != null)
+                {
+                    parent = TranslateParentItem(parent, user);
+                }
+
+                baseItemDtos.Add(_dtoService.GetBaseItemDto(parent, dtoOptions, user));
+
+                parent = parent.GetParent();
+            }
+
+            return baseItemDtos;
+        }
+
+        /// <summary>
+        /// Gets a list of physical paths from virtual folders.
+        /// </summary>
+        /// <response code="200">Physical paths returned.</response>
+        /// <returns>List of physical paths.</returns>
+        [HttpGet("/Library/PhysicalPaths")]
+        [Authorize(Policy = Policies.RequiresElevation)]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        public ActionResult<IEnumerable<string>> GetPhysicalPaths()
+        {
+            return Ok(_libraryManager.RootFolder.Children
+                .SelectMany(c => c.PhysicalLocations));
+        }
+
+        /// <summary>
+        /// Gets all user media folders.
+        /// </summary>
+        /// <param name="isHidden">Optional. Filter by folders that are marked hidden, or not.</param>
+        /// <response code="200">Media folders returned.</response>
+        /// <returns>List of user media folders.</returns>
+        [HttpGet("/Library/MediaFolders")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        public ActionResult<QueryResult<BaseItemDto>> GetMediaFolders([FromQuery] bool? isHidden)
+        {
+            var items = _libraryManager.GetUserRootFolder().Children.Concat(_libraryManager.RootFolder.VirtualChildren).OrderBy(i => i.SortName).ToList();
+
+            if (isHidden.HasValue)
+            {
+                var val = isHidden.Value;
+
+                items = items.Where(i => i.IsHidden == val).ToList();
+            }
+
+            var dtoOptions = new DtoOptions().AddClientFields(Request);
+            var result = new QueryResult<BaseItemDto>
+            {
+                TotalRecordCount = items.Count,
+                Items = items.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions)).ToArray()
+            };
+
+            return result;
+        }
+
+        /// <summary>
+        /// Reports that new episodes of a series have been added by an external source.
+        /// </summary>
+        /// <param name="tvdbId">The tvdbId.</param>
+        /// <response code="204">Report success.</response>
+        /// <returns>A <see cref="NoContentResult"/>.</returns>
+        [HttpPost("/Library/Series/Added")]
+        [HttpPost("/Library/Series/Updated")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status204NoContent)]
+        public ActionResult PostUpdatedSeries([FromQuery] string tvdbId)
+        {
+            var series = _libraryManager.GetItemList(new InternalItemsQuery
+            {
+                IncludeItemTypes = new[] { nameof(Series) },
+                DtoOptions = new DtoOptions(false)
+                {
+                    EnableImages = false
+                }
+            }).Where(i => string.Equals(tvdbId, i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Tvdb), StringComparison.OrdinalIgnoreCase)).ToArray();
+
+            foreach (var item in series)
+            {
+                _libraryMonitor.ReportFileSystemChanged(item.Path);
+            }
+
+            return NoContent();
+        }
+
+        /// <summary>
+        /// Reports that new movies have been added by an external source.
+        /// </summary>
+        /// <param name="tmdbId">The tmdbId.</param>
+        /// <param name="imdbId">The imdbId.</param>
+        /// <response code="204">Report success.</response>
+        /// <returns>A <see cref="NoContentResult"/>.</returns>
+        [HttpPost("/Library/Movies/Added")]
+        [HttpPost("/Library/Movies/Updated")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status204NoContent)]
+        public ActionResult PostUpdatedMovies([FromRoute] string tmdbId, [FromRoute] string imdbId)
+        {
+            var movies = _libraryManager.GetItemList(new InternalItemsQuery
+            {
+                IncludeItemTypes = new[] { nameof(Movie) },
+                DtoOptions = new DtoOptions(false)
+                {
+                    EnableImages = false
+                }
+            });
+
+            if (!string.IsNullOrWhiteSpace(imdbId))
+            {
+                movies = movies.Where(i => string.Equals(imdbId, i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Imdb), StringComparison.OrdinalIgnoreCase)).ToList();
+            }
+            else if (!string.IsNullOrWhiteSpace(tmdbId))
+            {
+                movies = movies.Where(i => string.Equals(tmdbId, i.GetProviderId(MediaBrowser.Model.Entities.MetadataProvider.Tmdb), StringComparison.OrdinalIgnoreCase)).ToList();
+            }
+            else
+            {
+                movies = new List<BaseItem>();
+            }
+
+            foreach (var item in movies)
+            {
+                _libraryMonitor.ReportFileSystemChanged(item.Path);
+            }
+
+            return NoContent();
+        }
+
+        /// <summary>
+        /// Reports that new movies have been added by an external source.
+        /// </summary>
+        /// <param name="updates">A list of updated media paths.</param>
+        /// <response code="204">Report success.</response>
+        /// <returns>A <see cref="NoContentResult"/>.</returns>
+        [HttpPost("/Library/Media/Updated")]
+        [Authorize(Policy = Policies.DefaultAuthorization)]
+        [ProducesResponseType(StatusCodes.Status204NoContent)]
+        public ActionResult PostUpdatedMedia([FromBody, BindRequired] MediaUpdateInfoDto[] updates)
+        {
+            foreach (var item in updates)
+            {
+                _libraryMonitor.ReportFileSystemChanged(item.Path);
+            }
+
+            return NoContent();
+        }
+
+        /// <summary>
+        /// Downloads item media.
+        /// </summary>
+        /// <param name="itemId">The item id.</param>
+        /// <response code="200">Media downloaded.</response>
+        /// <response code="404">Item not found.</response>
+        /// <returns>A <see cref="FileResult"/> containing the media stream.</returns>
+        /// <exception cref="ArgumentException">User can't download or item can't be downloaded.</exception>
+        [HttpGet("/Items/{itemId}/Download")]
+        [Authorize(Policy = Policies.Download)]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        [ProducesResponseType(StatusCodes.Status404NotFound)]
+        public ActionResult GetDownload([FromRoute] Guid itemId)
+        {
+            var item = _libraryManager.GetItemById(itemId);
+            if (item == null)
+            {
+                return NotFound();
+            }
+
+            var auth = _authContext.GetAuthorizationInfo(Request);
+
+            var user = auth.User;
+
+            if (user != null)
+            {
+                if (!item.CanDownload(user))
+                {
+                    throw new ArgumentException("Item does not support downloading");
+                }
+            }
+            else
+            {
+                if (!item.CanDownload())
+                {
+                    throw new ArgumentException("Item does not support downloading");
+                }
+            }
+
+            if (user != null)
+            {
+                LogDownload(item, user, auth);
+            }
+
+            var path = item.Path;
+
+            // Quotes are valid in linux. They'll possibly cause issues here
+            var filename = (Path.GetFileName(path) ?? string.Empty).Replace("\"", string.Empty, StringComparison.Ordinal);
+            if (!string.IsNullOrWhiteSpace(filename))
+            {
+                // Kestrel doesn't support non-ASCII characters in headers
+                if (Regex.IsMatch(filename, @"[^\p{IsBasicLatin}]"))
+                {
+                    // Manually encoding non-ASCII characters, following https://tools.ietf.org/html/rfc5987#section-3.2.2
+                    filename = WebUtility.UrlEncode(filename);
+                }
+            }
+
+            // TODO determine non-ASCII validity.
+            using var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
+            return File(fileStream, MimeTypes.GetMimeType(path), filename);
+        }
+
+        /// <summary>
+        /// Gets similar items.
+        /// </summary>
+        /// <param name="itemId">The item id.</param>
+        /// <param name="excludeArtistIds">Exclude artist ids.</param>
+        /// <param name="enableImages">(Unused) Optional. include image information in output.</param>
+        /// <param name="enableUserData">(Unused) Optional. include user data.</param>
+        /// <param name="imageTypeLimit">(Unused) Optional. the max number of images to return, per image type.</param>
+        /// <param name="enableImageTypes">(Unused) Optional. The image types to include in the output.</param>
+        /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
+        /// <param name="limit">Optional. The maximum number of records to return.</param>
+        /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param>
+        /// <response code="200">Similar items returned.</response>
+        /// <returns>A <see cref="QueryResult{BaseItemDto}"/> containing the similar items.</returns>
+        [HttpGet("/Artists/{itemId}/Similar")]
+        [HttpGet("/Items/{itemId}/Similar")]
+        [HttpGet("/Albums/{itemId}/Similar")]
+        [HttpGet("/Shows/{itemId}/Similar")]
+        [HttpGet("/Movies/{itemId}/Similar")]
+        [HttpGet("/Trailers/{itemId}/Similar")]
+        [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableImages", Justification = "Imported from ServiceStack")]
+        [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableUserData", Justification = "Imported from ServiceStack")]
+        [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageTypeLimit", Justification = "Imported from ServiceStack")]
+        [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableImageTypes", Justification = "Imported from ServiceStack")]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        public ActionResult<QueryResult<BaseItemDto>> GetSimilarItems(
+            [FromRoute] Guid itemId,
+            [FromQuery] string excludeArtistIds,
+            [FromQuery] bool? enableImages,
+            [FromQuery] bool? enableUserData,
+            [FromQuery] int? imageTypeLimit,
+            [FromQuery] string enableImageTypes,
+            [FromQuery] Guid userId,
+            [FromQuery] int? limit,
+            [FromQuery] string fields)
+        {
+            var item = itemId.Equals(Guid.Empty)
+                ? (!userId.Equals(Guid.Empty)
+                    ? _libraryManager.GetUserRootFolder()
+                    : _libraryManager.RootFolder)
+                : _libraryManager.GetItemById(itemId);
+
+            var program = item as IHasProgramAttributes;
+            var isMovie = item is MediaBrowser.Controller.Entities.Movies.Movie || (program != null && program.IsMovie) || item is Trailer;
+            if (program != null && program.IsSeries)
+            {
+                return GetSimilarItemsResult(
+                    item,
+                    excludeArtistIds,
+                    userId,
+                    limit,
+                    fields,
+                    new[] { nameof(Series) },
+                    false);
+            }
+
+            if (item is MediaBrowser.Controller.Entities.TV.Episode || (item is IItemByName && !(item is MusicArtist)))
+            {
+                return new QueryResult<BaseItemDto>();
+            }
+
+            return GetSimilarItemsResult(
+                item,
+                excludeArtistIds,
+                userId,
+                limit,
+                fields,
+                new[] { item.GetType().Name },
+                isMovie);
+        }
+
+        /// <summary>
+        /// Gets the library options info.
+        /// </summary>
+        /// <param name="libraryContentType">Library content type.</param>
+        /// <param name="isNewLibrary">Whether this is a new library.</param>
+        /// <response code="200">Library options info returned.</response>
+        /// <returns>Library options info.</returns>
+        [HttpGet("/Libraries/AvailableOptions")]
+        [Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
+        [ProducesResponseType(StatusCodes.Status200OK)]
+        public ActionResult<LibraryOptionsResultDto> GetLibraryOptionsInfo([FromQuery] string libraryContentType, [FromQuery] bool isNewLibrary)
+        {
+            var result = new LibraryOptionsResultDto();
+
+            var types = GetRepresentativeItemTypes(libraryContentType);
+            var typesList = types.ToList();
+
+            var plugins = _providerManager.GetAllMetadataPlugins()
+                .Where(i => types.Contains(i.ItemType, StringComparer.OrdinalIgnoreCase))
+                .OrderBy(i => typesList.IndexOf(i.ItemType))
+                .ToList();
+
+            result.MetadataSavers = plugins
+                .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataSaver))
+                .Select(i => new LibraryOptionInfoDto
+                {
+                    Name = i.Name,
+                    DefaultEnabled = IsSaverEnabledByDefault(i.Name, types, isNewLibrary)
+                })
+                .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
+                .Select(x => x.First())
+                .ToArray();
+
+            result.MetadataReaders = plugins
+                .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.LocalMetadataProvider))
+                .Select(i => new LibraryOptionInfoDto
+                {
+                    Name = i.Name,
+                    DefaultEnabled = true
+                })
+                .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
+                .Select(x => x.First())
+                .ToArray();
+
+            result.SubtitleFetchers = plugins
+                .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.SubtitleFetcher))
+                .Select(i => new LibraryOptionInfoDto
+                {
+                    Name = i.Name,
+                    DefaultEnabled = true
+                })
+                .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
+                .Select(x => x.First())
+                .ToArray();
+
+            var typeOptions = new List<LibraryTypeOptionsDto>();
+
+            foreach (var type in types)
+            {
+                TypeOptions.DefaultImageOptions.TryGetValue(type, out var defaultImageOptions);
+
+                typeOptions.Add(new LibraryTypeOptionsDto
+                {
+                    Type = type,
+
+                    MetadataFetchers = plugins
+                    .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
+                    .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataFetcher))
+                    .Select(i => new LibraryOptionInfoDto
+                    {
+                        Name = i.Name,
+                        DefaultEnabled = IsMetadataFetcherEnabledByDefault(i.Name, type, isNewLibrary)
+                    })
+                    .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
+                    .Select(x => x.First())
+                    .ToArray(),
+
+                    ImageFetchers = plugins
+                    .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
+                    .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.ImageFetcher))
+                    .Select(i => new LibraryOptionInfoDto
+                    {
+                        Name = i.Name,
+                        DefaultEnabled = IsImageFetcherEnabledByDefault(i.Name, type, isNewLibrary)
+                    })
+                    .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
+                    .Select(x => x.First())
+                    .ToArray(),
+
+                    SupportedImageTypes = plugins
+                    .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
+                    .SelectMany(i => i.SupportedImageTypes ?? Array.Empty<ImageType>())
+                    .Distinct()
+                    .ToArray(),
+
+                    DefaultImageOptions = defaultImageOptions ?? Array.Empty<ImageOption>()
+                });
+            }
+
+            result.TypeOptions = typeOptions.ToArray();
+
+            return result;
+        }
+
+        private int GetCount(Type type, User? user, bool? isFavorite)
+        {
+            var query = new InternalItemsQuery(user)
+            {
+                IncludeItemTypes = new[] { type.Name },
+                Limit = 0,
+                Recursive = true,
+                IsVirtualItem = false,
+                IsFavorite = isFavorite,
+                DtoOptions = new DtoOptions(false)
+                {
+                    EnableImages = false
+                }
+            };
+
+            return _libraryManager.GetItemsResult(query).TotalRecordCount;
+        }
+
+        private BaseItem TranslateParentItem(BaseItem item, User user)
+        {
+            return item.GetParent() is AggregateFolder
+                ? _libraryManager.GetUserRootFolder().GetChildren(user, true)
+                    .FirstOrDefault(i => i.PhysicalLocations.Contains(item.Path))
+                : item;
+        }
+
+        private void LogDownload(BaseItem item, User user, AuthorizationInfo auth)
+        {
+            try
+            {
+                _activityManager.Create(new ActivityLog(
+                    string.Format(CultureInfo.InvariantCulture, _localization.GetLocalizedString("UserDownloadingItemWithValues"), user.Username, item.Name),
+                    "UserDownloadingContent",
+                    auth.UserId)
+                {
+                    ShortOverview = string.Format(CultureInfo.InvariantCulture, _localization.GetLocalizedString("AppDeviceValues"), auth.Client, auth.Device),
+                });
+            }
+            catch
+            {
+                // Logged at lower levels
+            }
+        }
+
+        private QueryResult<BaseItemDto> GetSimilarItemsResult(
+            BaseItem item,
+            string excludeArtistIds,
+            Guid userId,
+            int? limit,
+            string fields,
+            string[] includeItemTypes,
+            bool isMovie)
+        {
+            var user = !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId) : null;
+            var dtoOptions = new DtoOptions()
+                .AddItemFields(fields)
+                .AddClientFields(Request);
+
+            var query = new InternalItemsQuery(user)
+            {
+                Limit = limit,
+                IncludeItemTypes = includeItemTypes,
+                IsMovie = isMovie,
+                SimilarTo = item,
+                DtoOptions = dtoOptions,
+                EnableTotalRecordCount = !isMovie,
+                EnableGroupByMetadataKey = isMovie
+            };
+
+            // ExcludeArtistIds
+            if (!string.IsNullOrEmpty(excludeArtistIds))
+            {
+                query.ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds);
+            }
+
+            List<BaseItem> itemsResult;
+
+            if (isMovie)
+            {
+                var itemTypes = new List<string> { nameof(MediaBrowser.Controller.Entities.Movies.Movie) };
+                if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
+                {
+                    itemTypes.Add(nameof(Trailer));
+                    itemTypes.Add(nameof(LiveTvProgram));
+                }
+
+                query.IncludeItemTypes = itemTypes.ToArray();
+                itemsResult = _libraryManager.GetArtists(query).Items.Select(i => i.Item1).ToList();
+            }
+            else if (item is MusicArtist)
+            {
+                query.IncludeItemTypes = Array.Empty<string>();
+
+                itemsResult = _libraryManager.GetArtists(query).Items.Select(i => i.Item1).ToList();
+            }
+            else
+            {
+                itemsResult = _libraryManager.GetItemList(query);
+            }
+
+            var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);
+
+            var result = new QueryResult<BaseItemDto>
+            {
+                Items = returnList,
+                TotalRecordCount = itemsResult.Count
+            };
+
+            return result;
+        }
+
+        private static string[] GetRepresentativeItemTypes(string contentType)
+        {
+            return contentType switch
+            {
+                CollectionType.BoxSets => new[] { "BoxSet" },
+                CollectionType.Playlists => new[] { "Playlist" },
+                CollectionType.Movies => new[] { "Movie" },
+                CollectionType.TvShows => new[] { "Series", "Season", "Episode" },
+                CollectionType.Books => new[] { "Book" },
+                CollectionType.Music => new[] { "MusicArtist", "MusicAlbum", "Audio", "MusicVideo" },
+                CollectionType.HomeVideos => new[] { "Video", "Photo" },
+                CollectionType.Photos => new[] { "Video", "Photo" },
+                CollectionType.MusicVideos => new[] { "MusicVideo" },
+                _ => new[] { "Series", "Season", "Episode", "Movie" }
+            };
+        }
+
+        private bool IsSaverEnabledByDefault(string name, string[] itemTypes, bool isNewLibrary)
+        {
+            if (isNewLibrary)
+            {
+                return false;
+            }
+
+            var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
+                .Where(i => itemTypes.Contains(i.ItemType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+                .ToArray();
+
+            return metadataOptions.Length == 0 || metadataOptions.Any(i => !i.DisabledMetadataSavers.Contains(name, StringComparer.OrdinalIgnoreCase));
+        }
+
+        private bool IsMetadataFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
+        {
+            if (isNewLibrary)
+            {
+                if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
+                {
+                    return !(string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)
+                         || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)
+                         || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase));
+                }
+
+                return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)
+                   || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)
+                   || string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase);
+            }
+
+            var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
+                .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
+                .ToArray();
+
+            return metadataOptions.Length == 0
+               || metadataOptions.Any(i => !i.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
+        }
+
+        private bool IsImageFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
+        {
+            if (isNewLibrary)
+            {
+                if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
+                {
+                    return !string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase)
+                           && !string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)
+                           && !string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)
+                           && !string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase);
+                }
+
+                return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)
+                       || string.Equals(name, "Screen Grabber", StringComparison.OrdinalIgnoreCase)
+                       || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)
+                       || string.Equals(name, "Image Extractor", StringComparison.OrdinalIgnoreCase);
+            }
+
+            var metadataOptions = _serverConfigurationManager.Configuration.MetadataOptions
+                .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
+                .ToArray();
+
+            if (metadataOptions.Length == 0)
+            {
+                return true;
+            }
+
+            return metadataOptions.Any(i => !i.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
+        }
+    }
+}

+ 1 - 1
Jellyfin.Api/Helpers/RequestHelpers.cs

@@ -87,7 +87,7 @@ namespace Jellyfin.Api.Helpers
                 return Array.Empty<Guid>();
             }
 
-            return value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
+            return Split(value, ',', true)
                 .Select(i => new Guid(i))
                 .ToArray();
         }

+ 18 - 0
Jellyfin.Api/Models/LibraryDtos/LibraryOptionInfoDto.cs

@@ -0,0 +1,18 @@
+namespace Jellyfin.Api.Models.LibraryDtos
+{
+    /// <summary>
+    /// Library option info dto.
+    /// </summary>
+    public class LibraryOptionInfoDto
+    {
+        /// <summary>
+        /// Gets or sets name.
+        /// </summary>
+        public string? Name { get; set; }
+
+        /// <summary>
+        /// Gets or sets a value indicating whether default enabled.
+        /// </summary>
+        public bool DefaultEnabled { get; set; }
+    }
+}

+ 34 - 0
Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs

@@ -0,0 +1,34 @@
+using System.Diagnostics.CodeAnalysis;
+
+namespace Jellyfin.Api.Models.LibraryDtos
+{
+    /// <summary>
+    /// Library options result dto.
+    /// </summary>
+    public class LibraryOptionsResultDto
+    {
+        /// <summary>
+        /// Gets or sets the metadata savers.
+        /// </summary>
+        [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "MetadataSavers", Justification = "Imported from ServiceStack")]
+        public LibraryOptionInfoDto[] MetadataSavers { get; set; } = null!;
+
+        /// <summary>
+        /// Gets or sets the metadata readers.
+        /// </summary>
+        [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "MetadataReaders", Justification = "Imported from ServiceStack")]
+        public LibraryOptionInfoDto[] MetadataReaders { get; set; } = null!;
+
+        /// <summary>
+        /// Gets or sets the subtitle fetchers.
+        /// </summary>
+        [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "SubtitleFetchers", Justification = "Imported from ServiceStack")]
+        public LibraryOptionInfoDto[] SubtitleFetchers { get; set; } = null!;
+
+        /// <summary>
+        /// Gets or sets the type options.
+        /// </summary>
+        [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "TypeOptions", Justification = "Imported from ServiceStack")]
+        public LibraryTypeOptionsDto[] TypeOptions { get; set; } = null!;
+    }
+}

+ 41 - 0
Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs

@@ -0,0 +1,41 @@
+using System.Diagnostics.CodeAnalysis;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.Entities;
+
+namespace Jellyfin.Api.Models.LibraryDtos
+{
+    /// <summary>
+    /// Library type options dto.
+    /// </summary>
+    public class LibraryTypeOptionsDto
+    {
+        /// <summary>
+        /// Gets or sets the type.
+        /// </summary>
+        public string? Type { get; set; }
+
+        /// <summary>
+        /// Gets or sets the metadata fetchers.
+        /// </summary>
+        [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "MetadataFetchers", Justification = "Imported from ServiceStack")]
+        public LibraryOptionInfoDto[] MetadataFetchers { get; set; } = null!;
+
+        /// <summary>
+        /// Gets or sets the image fetchers.
+        /// </summary>
+        [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "ImageFetchers", Justification = "Imported from ServiceStack")]
+        public LibraryOptionInfoDto[] ImageFetchers { get; set; } = null!;
+
+        /// <summary>
+        /// Gets or sets the supported image types.
+        /// </summary>
+        [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "SupportedImageTypes", Justification = "Imported from ServiceStack")]
+        public ImageType[] SupportedImageTypes { get; set; } = null!;
+
+        /// <summary>
+        /// Gets or sets the default image options.
+        /// </summary>
+        [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "DefaultImageOptions", Justification = "Imported from ServiceStack")]
+        public ImageOption[] DefaultImageOptions { get; set; } = null!;
+    }
+}

+ 19 - 0
Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoDto.cs

@@ -0,0 +1,19 @@
+namespace Jellyfin.Api.Models.LibraryDtos
+{
+    /// <summary>
+    /// Media Update Info Dto.
+    /// </summary>
+    public class MediaUpdateInfoDto
+    {
+        /// <summary>
+        /// Gets or sets media path.
+        /// </summary>
+        public string? Path { get; set; }
+
+        /// <summary>
+        /// Gets or sets media update type.
+        /// Created, Modified, Deleted.
+        /// </summary>
+        public string? UpdateType { get; set; }
+    }
+}

+ 9 - 0
Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs

@@ -6,6 +6,7 @@ using System.Reflection;
 using Jellyfin.Api;
 using Jellyfin.Api.Auth;
 using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
+using Jellyfin.Api.Auth.DownloadPolicy;
 using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy;
 using Jellyfin.Api.Auth.IgnoreSchedulePolicy;
 using Jellyfin.Api.Auth.LocalAccessPolicy;
@@ -39,6 +40,7 @@ namespace Jellyfin.Server.Extensions
         public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection)
         {
             serviceCollection.AddSingleton<IAuthorizationHandler, DefaultAuthorizationHandler>();
+            serviceCollection.AddSingleton<IAuthorizationHandler, DownloadHandler>();
             serviceCollection.AddSingleton<IAuthorizationHandler, FirstTimeSetupOrElevatedHandler>();
             serviceCollection.AddSingleton<IAuthorizationHandler, IgnoreScheduleHandler>();
             serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessHandler>();
@@ -52,6 +54,13 @@ namespace Jellyfin.Server.Extensions
                         policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
                         policy.AddRequirements(new DefaultAuthorizationRequirement());
                     });
+                options.AddPolicy(
+                    Policies.Download,
+                    policy =>
+                    {
+                        policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication);
+                        policy.AddRequirements(new DownloadRequirement());
+                    });
                 options.AddPolicy(
                     Policies.FirstTimeSetupOrElevated,
                     policy =>

+ 0 - 1116
MediaBrowser.Api/Library/LibraryService.cs

@@ -1,1116 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Text.RegularExpressions;
-using System.Threading;
-using System.Threading.Tasks;
-using Jellyfin.Data.Entities;
-using MediaBrowser.Api.Movies;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Progress;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.Audio;
-using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Activity;
-using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
-using Microsoft.Net.Http.Headers;
-using Book = MediaBrowser.Controller.Entities.Book;
-using Episode = MediaBrowser.Controller.Entities.TV.Episode;
-using MetadataProvider = MediaBrowser.Model.Entities.MetadataProvider;
-using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
-using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
-using Series = MediaBrowser.Controller.Entities.TV.Series;
-
-namespace MediaBrowser.Api.Library
-{
-    [Route("/Items/{Id}/File", "GET", Summary = "Gets the original file of an item")]
-    [Authenticated]
-    public class GetFile
-    {
-        /// <summary>
-        /// Gets or sets the id.
-        /// </summary>
-        /// <value>The id.</value>
-        [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
-        public string Id { get; set; }
-    }
-
-    /// <summary>
-    /// Class GetCriticReviews
-    /// </summary>
-    [Route("/Items/{Id}/CriticReviews", "GET", Summary = "Gets critic reviews for an item")]
-    [Authenticated]
-    public class GetCriticReviews : IReturn<QueryResult<BaseItemDto>>
-    {
-        /// <summary>
-        /// Gets or sets the id.
-        /// </summary>
-        /// <value>The id.</value>
-        [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
-        public string Id { get; set; }
-
-        /// <summary>
-        /// Skips over a given number of items within the results. Use for paging.
-        /// </summary>
-        /// <value>The start index.</value>
-        [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
-        public int? StartIndex { get; set; }
-
-        /// <summary>
-        /// The maximum number of items to return
-        /// </summary>
-        /// <value>The limit.</value>
-        [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
-        public int? Limit { get; set; }
-    }
-
-    /// <summary>
-    /// Class GetThemeSongs
-    /// </summary>
-    [Route("/Items/{Id}/ThemeSongs", "GET", Summary = "Gets theme songs for an item")]
-    [Authenticated]
-    public class GetThemeSongs : IReturn<ThemeMediaResult>
-    {
-        /// <summary>
-        /// Gets or sets the user id.
-        /// </summary>
-        /// <value>The user id.</value>
-        [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
-        public Guid UserId { get; set; }
-
-        /// <summary>
-        /// Gets or sets the id.
-        /// </summary>
-        /// <value>The id.</value>
-        [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
-        public string Id { get; set; }
-
-        [ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
-        public bool InheritFromParent { get; set; }
-    }
-
-    /// <summary>
-    /// Class GetThemeVideos
-    /// </summary>
-    [Route("/Items/{Id}/ThemeVideos", "GET", Summary = "Gets theme videos for an item")]
-    [Authenticated]
-    public class GetThemeVideos : IReturn<ThemeMediaResult>
-    {
-        /// <summary>
-        /// Gets or sets the user id.
-        /// </summary>
-        /// <value>The user id.</value>
-        [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
-        public Guid UserId { get; set; }
-
-        /// <summary>
-        /// Gets or sets the id.
-        /// </summary>
-        /// <value>The id.</value>
-        [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
-        public string Id { get; set; }
-
-        [ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
-        public bool InheritFromParent { get; set; }
-    }
-
-    /// <summary>
-    /// Class GetThemeVideos
-    /// </summary>
-    [Route("/Items/{Id}/ThemeMedia", "GET", Summary = "Gets theme videos and songs for an item")]
-    [Authenticated]
-    public class GetThemeMedia : IReturn<AllThemeMediaResult>
-    {
-        /// <summary>
-        /// Gets or sets the user id.
-        /// </summary>
-        /// <value>The user id.</value>
-        [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
-        public Guid UserId { get; set; }
-
-        /// <summary>
-        /// Gets or sets the id.
-        /// </summary>
-        /// <value>The id.</value>
-        [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
-        public string Id { get; set; }
-
-        [ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
-        public bool InheritFromParent { get; set; }
-    }
-
-    [Route("/Library/Refresh", "POST", Summary = "Starts a library scan")]
-    [Authenticated(Roles = "Admin")]
-    public class RefreshLibrary : IReturnVoid
-    {
-    }
-
-    [Route("/Items/{Id}", "DELETE", Summary = "Deletes an item from the library and file system")]
-    [Authenticated]
-    public class DeleteItem : IReturnVoid
-    {
-        [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
-        public string Id { get; set; }
-    }
-
-    [Route("/Items", "DELETE", Summary = "Deletes an item from the library and file system")]
-    [Authenticated]
-    public class DeleteItems : IReturnVoid
-    {
-        [ApiMember(Name = "Ids", Description = "Ids", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "DELETE")]
-        public string Ids { get; set; }
-    }
-
-    [Route("/Items/Counts", "GET")]
-    [Authenticated]
-    public class GetItemCounts : IReturn<ItemCounts>
-    {
-        [ApiMember(Name = "UserId", Description = "Optional. Get counts from a specific user's library.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
-        public Guid UserId { get; set; }
-
-        [ApiMember(Name = "IsFavorite", Description = "Optional. Get counts of favorite items", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
-        public bool? IsFavorite { get; set; }
-    }
-
-    [Route("/Items/{Id}/Ancestors", "GET", Summary = "Gets all parents of an item")]
-    [Authenticated]
-    public class GetAncestors : IReturn<BaseItemDto[]>
-    {
-        /// <summary>
-        /// Gets or sets the user id.
-        /// </summary>
-        /// <value>The user id.</value>
-        [ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
-        public Guid UserId { get; set; }
-
-        /// <summary>
-        /// Gets or sets the id.
-        /// </summary>
-        /// <value>The id.</value>
-        [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
-        public string Id { get; set; }
-    }
-
-    /// <summary>
-    /// Class GetPhyscialPaths
-    /// </summary>
-    [Route("/Library/PhysicalPaths", "GET", Summary = "Gets a list of physical paths from virtual folders")]
-    [Authenticated(Roles = "Admin")]
-    public class GetPhyscialPaths : IReturn<List<string>>
-    {
-    }
-
-    [Route("/Library/MediaFolders", "GET", Summary = "Gets all user media folders.")]
-    [Authenticated]
-    public class GetMediaFolders : IReturn<QueryResult<BaseItemDto>>
-    {
-        [ApiMember(Name = "IsHidden", Description = "Optional. Filter by folders that are marked hidden, or not.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
-        public bool? IsHidden { get; set; }
-    }
-
-    [Route("/Library/Series/Added", "POST", Summary = "Reports that new episodes of a series have been added by an external source")]
-    [Route("/Library/Series/Updated", "POST", Summary = "Reports that new episodes of a series have been added by an external source")]
-    [Authenticated]
-    public class PostUpdatedSeries : IReturnVoid
-    {
-        [ApiMember(Name = "TvdbId", Description = "Tvdb Id", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "POST")]
-        public string TvdbId { get; set; }
-    }
-
-    [Route("/Library/Movies/Added", "POST", Summary = "Reports that new movies have been added by an external source")]
-    [Route("/Library/Movies/Updated", "POST", Summary = "Reports that new movies have been added by an external source")]
-    [Authenticated]
-    public class PostUpdatedMovies : IReturnVoid
-    {
-        [ApiMember(Name = "TmdbId", Description = "Tmdb Id", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "POST")]
-        public string TmdbId { get; set; }
-        [ApiMember(Name = "ImdbId", Description = "Imdb Id", IsRequired = false, DataType = "string", ParameterType = "path", Verb = "POST")]
-        public string ImdbId { get; set; }
-    }
-
-    public class MediaUpdateInfo
-    {
-        public string Path { get; set; }
-
-        // Created, Modified, Deleted
-        public string UpdateType { get; set; }
-    }
-
-    [Route("/Library/Media/Updated", "POST", Summary = "Reports that new movies have been added by an external source")]
-    [Authenticated]
-    public class PostUpdatedMedia : IReturnVoid
-    {
-        [ApiMember(Name = "Updates", Description = "A list of updated media paths", IsRequired = false, DataType = "string", ParameterType = "body", Verb = "POST")]
-        public List<MediaUpdateInfo> Updates { get; set; }
-    }
-
-    [Route("/Items/{Id}/Download", "GET", Summary = "Downloads item media")]
-    [Authenticated(Roles = "download")]
-    public class GetDownload
-    {
-        /// <summary>
-        /// Gets or sets the id.
-        /// </summary>
-        /// <value>The id.</value>
-        [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
-        public string Id { get; set; }
-    }
-
-    [Route("/Artists/{Id}/Similar", "GET", Summary = "Finds albums similar to a given album.")]
-    [Route("/Items/{Id}/Similar", "GET", Summary = "Gets similar items")]
-    [Route("/Albums/{Id}/Similar", "GET", Summary = "Finds albums similar to a given album.")]
-    [Route("/Shows/{Id}/Similar", "GET", Summary = "Finds tv shows similar to a given one.")]
-    [Route("/Movies/{Id}/Similar", "GET", Summary = "Finds movies and trailers similar to a given movie.")]
-    [Route("/Trailers/{Id}/Similar", "GET", Summary = "Finds movies and trailers similar to a given trailer.")]
-    [Authenticated]
-    public class GetSimilarItems : BaseGetSimilarItemsFromItem
-    {
-    }
-
-    [Route("/Libraries/AvailableOptions", "GET")]
-    [Authenticated(AllowBeforeStartupWizard = true)]
-    public class GetLibraryOptionsInfo : IReturn<LibraryOptionsResult>
-    {
-        public string LibraryContentType { get; set; }
-        public bool IsNewLibrary { get; set; }
-    }
-
-    public class LibraryOptionInfo
-    {
-        public string Name { get; set; }
-        public bool DefaultEnabled { get; set; }
-    }
-
-    public class LibraryOptionsResult
-    {
-        public LibraryOptionInfo[] MetadataSavers { get; set; }
-        public LibraryOptionInfo[] MetadataReaders { get; set; }
-        public LibraryOptionInfo[] SubtitleFetchers { get; set; }
-        public LibraryTypeOptions[] TypeOptions { get; set; }
-    }
-
-    public class LibraryTypeOptions
-    {
-        public string Type { get; set; }
-        public LibraryOptionInfo[] MetadataFetchers { get; set; }
-        public LibraryOptionInfo[] ImageFetchers { get; set; }
-        public ImageType[] SupportedImageTypes { get; set; }
-        public ImageOption[] DefaultImageOptions { get; set; }
-    }
-
-    /// <summary>
-    /// Class LibraryService
-    /// </summary>
-    public class LibraryService : BaseApiService
-    {
-        private readonly IProviderManager _providerManager;
-        private readonly ILibraryManager _libraryManager;
-        private readonly IUserManager _userManager;
-        private readonly IDtoService _dtoService;
-        private readonly IAuthorizationContext _authContext;
-        private readonly IActivityManager _activityManager;
-        private readonly ILocalizationManager _localization;
-        private readonly ILibraryMonitor _libraryMonitor;
-
-        private readonly ILogger<MoviesService> _moviesServiceLogger;
-
-        /// <summary>
-        /// Initializes a new instance of the <see cref="LibraryService" /> class.
-        /// </summary>
-        public LibraryService(
-            ILogger<LibraryService> logger,
-            ILogger<MoviesService> moviesServiceLogger,
-            IServerConfigurationManager serverConfigurationManager,
-            IHttpResultFactory httpResultFactory,
-            IProviderManager providerManager,
-            ILibraryManager libraryManager,
-            IUserManager userManager,
-            IDtoService dtoService,
-            IAuthorizationContext authContext,
-            IActivityManager activityManager,
-            ILocalizationManager localization,
-            ILibraryMonitor libraryMonitor)
-            : base(logger, serverConfigurationManager, httpResultFactory)
-        {
-            _providerManager = providerManager;
-            _libraryManager = libraryManager;
-            _userManager = userManager;
-            _dtoService = dtoService;
-            _authContext = authContext;
-            _activityManager = activityManager;
-            _localization = localization;
-            _libraryMonitor = libraryMonitor;
-            _moviesServiceLogger = moviesServiceLogger;
-        }
-
-        // Content Types available for each Library
-        private string[] GetRepresentativeItemTypes(string contentType)
-        {
-            return contentType switch
-            {
-                CollectionType.BoxSets => new[] {"BoxSet"},
-                CollectionType.Playlists => new[] {"Playlist"},
-                CollectionType.Movies => new[] {"Movie"},
-                CollectionType.TvShows => new[] {"Series", "Season", "Episode"},
-                CollectionType.Books => new[] {"Book"},
-                CollectionType.Music => new[] {"MusicArtist", "MusicAlbum", "Audio", "MusicVideo"},
-                CollectionType.HomeVideos => new[] {"Video", "Photo"},
-                CollectionType.Photos => new[] {"Video", "Photo"},
-                CollectionType.MusicVideos => new[] {"MusicVideo"},
-                _ => new[] {"Series", "Season", "Episode", "Movie"}
-            };
-        }
-
-        private bool IsSaverEnabledByDefault(string name, string[] itemTypes, bool isNewLibrary)
-        {
-            if (isNewLibrary)
-            {
-                return false;
-            }
-
-            var metadataOptions = ServerConfigurationManager.Configuration.MetadataOptions
-                .Where(i => itemTypes.Contains(i.ItemType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
-                .ToArray();
-
-            if (metadataOptions.Length == 0)
-            {
-                return true;
-            }
-
-            return metadataOptions.Any(i => !i.DisabledMetadataSavers.Contains(name, StringComparer.OrdinalIgnoreCase));
-        }
-
-        private bool IsMetadataFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
-        {
-            if (isNewLibrary)
-            {
-                if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
-                {
-                    return !(string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)
-                         || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)
-                         || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase));
-                }
-
-                return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)
-                   || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)
-                   || string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase);
-            }
-
-            var metadataOptions = ServerConfigurationManager.Configuration.MetadataOptions
-                .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
-                .ToArray();
-
-            return metadataOptions.Length == 0
-               || metadataOptions.Any(i => !i.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
-        }
-
-        private bool IsImageFetcherEnabledByDefault(string name, string type, bool isNewLibrary)
-        {
-            if (isNewLibrary)
-            {
-                if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase))
-                {
-                    return !string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase)
-                           && !string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)
-                           && !string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)
-                           && !string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase);
-                }
-
-                return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)
-                       || string.Equals(name, "Screen Grabber", StringComparison.OrdinalIgnoreCase)
-                       || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)
-                       || string.Equals(name, "Image Extractor", StringComparison.OrdinalIgnoreCase);
-            }
-
-            var metadataOptions = ServerConfigurationManager.Configuration.MetadataOptions
-                .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
-                .ToArray();
-
-            if (metadataOptions.Length == 0)
-            {
-                return true;
-            }
-
-            return metadataOptions.Any(i => !i.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase));
-        }
-
-        public object Get(GetLibraryOptionsInfo request)
-        {
-            var result = new LibraryOptionsResult();
-
-            var types = GetRepresentativeItemTypes(request.LibraryContentType);
-            var isNewLibrary = request.IsNewLibrary;
-            var typesList = types.ToList();
-
-            var plugins = _providerManager.GetAllMetadataPlugins()
-                .Where(i => types.Contains(i.ItemType, StringComparer.OrdinalIgnoreCase))
-                .OrderBy(i => typesList.IndexOf(i.ItemType))
-                .ToList();
-
-            result.MetadataSavers = plugins
-                .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataSaver))
-                .Select(i => new LibraryOptionInfo
-                {
-                    Name = i.Name,
-                    DefaultEnabled = IsSaverEnabledByDefault(i.Name, types, isNewLibrary)
-                })
-                .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
-                .Select(x => x.First())
-                .ToArray();
-
-            result.MetadataReaders = plugins
-                .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.LocalMetadataProvider))
-                .Select(i => new LibraryOptionInfo
-                {
-                    Name = i.Name,
-                    DefaultEnabled = true
-                })
-                .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
-                .Select(x => x.First())
-                .ToArray();
-
-            result.SubtitleFetchers = plugins
-                .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.SubtitleFetcher))
-                .Select(i => new LibraryOptionInfo
-                {
-                    Name = i.Name,
-                    DefaultEnabled = true
-                })
-                .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
-                .Select(x => x.First())
-                .ToArray();
-
-            var typeOptions = new List<LibraryTypeOptions>();
-
-            foreach (var type in types)
-            {
-                TypeOptions.DefaultImageOptions.TryGetValue(type, out var defaultImageOptions);
-
-                typeOptions.Add(new LibraryTypeOptions
-                {
-                    Type = type,
-
-                    MetadataFetchers = plugins
-                    .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
-                    .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.MetadataFetcher))
-                    .Select(i => new LibraryOptionInfo
-                    {
-                        Name = i.Name,
-                        DefaultEnabled = IsMetadataFetcherEnabledByDefault(i.Name, type, isNewLibrary)
-                    })
-                    .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
-                    .Select(x => x.First())
-                    .ToArray(),
-
-                    ImageFetchers = plugins
-                    .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
-                    .SelectMany(i => i.Plugins.Where(p => p.Type == MetadataPluginType.ImageFetcher))
-                    .Select(i => new LibraryOptionInfo
-                    {
-                        Name = i.Name,
-                        DefaultEnabled = IsImageFetcherEnabledByDefault(i.Name, type, isNewLibrary)
-                    })
-                    .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
-                    .Select(x => x.First())
-                    .ToArray(),
-
-                    SupportedImageTypes = plugins
-                    .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase))
-                    .SelectMany(i => i.SupportedImageTypes ?? Array.Empty<ImageType>())
-                    .Distinct()
-                    .ToArray(),
-
-                    DefaultImageOptions = defaultImageOptions ?? Array.Empty<ImageOption>()
-                });
-            }
-
-            result.TypeOptions = typeOptions.ToArray();
-
-            return result;
-        }
-
-        public object Get(GetSimilarItems request)
-        {
-            var item = string.IsNullOrEmpty(request.Id) ?
-                (!request.UserId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() :
-                _libraryManager.RootFolder) : _libraryManager.GetItemById(request.Id);
-
-            var program = item as IHasProgramAttributes;
-
-            if (item is Movie || (program != null && program.IsMovie) || item is Trailer)
-            {
-                return new MoviesService(
-                    _moviesServiceLogger,
-                    ServerConfigurationManager,
-                    ResultFactory,
-                    _userManager,
-                    _libraryManager,
-                    _dtoService,
-                    _authContext)
-                {
-                    Request = Request,
-
-                }.GetSimilarItemsResult(request);
-            }
-
-            if (program != null && program.IsSeries)
-            {
-                return GetSimilarItemsResult(request, new[] { typeof(Series).Name });
-            }
-
-            if (item is Episode || (item is IItemByName && !(item is MusicArtist)))
-            {
-                return new QueryResult<BaseItemDto>();
-            }
-
-            return GetSimilarItemsResult(request, new[] { item.GetType().Name });
-        }
-
-        private QueryResult<BaseItemDto> GetSimilarItemsResult(BaseGetSimilarItemsFromItem request, string[] includeItemTypes)
-        {
-            var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
-            var item = string.IsNullOrEmpty(request.Id) ?
-                (!request.UserId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() :
-                _libraryManager.RootFolder) : _libraryManager.GetItemById(request.Id);
-
-            var dtoOptions = GetDtoOptions(_authContext, request);
-
-            var query = new InternalItemsQuery(user)
-            {
-                Limit = request.Limit,
-                IncludeItemTypes = includeItemTypes,
-                SimilarTo = item,
-                DtoOptions = dtoOptions,
-                EnableTotalRecordCount = false
-            };
-
-            // ExcludeArtistIds
-            if (!string.IsNullOrEmpty(request.ExcludeArtistIds))
-            {
-                query.ExcludeArtistIds = GetGuids(request.ExcludeArtistIds);
-            }
-
-            List<BaseItem> itemsResult;
-
-            if (item is MusicArtist)
-            {
-                query.IncludeItemTypes = Array.Empty<string>();
-
-                itemsResult = _libraryManager.GetArtists(query).Items.Select(i => i.Item1).ToList();
-            }
-            else
-            {
-                itemsResult = _libraryManager.GetItemList(query);
-            }
-
-            var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);
-
-            var result = new QueryResult<BaseItemDto>
-            {
-                Items = returnList,
-                TotalRecordCount = itemsResult.Count
-            };
-
-            return result;
-        }
-
-        public object Get(GetMediaFolders request)
-        {
-            var items = _libraryManager.GetUserRootFolder().Children.Concat(_libraryManager.RootFolder.VirtualChildren).OrderBy(i => i.SortName).ToList();
-
-            if (request.IsHidden.HasValue)
-            {
-                var val = request.IsHidden.Value;
-
-                items = items.Where(i => i.IsHidden == val).ToList();
-            }
-
-            var dtoOptions = GetDtoOptions(_authContext, request);
-
-            var result = new QueryResult<BaseItemDto>
-            {
-                TotalRecordCount = items.Count,
-
-                Items = items.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions)).ToArray()
-            };
-
-            return result;
-        }
-
-        public void Post(PostUpdatedSeries request)
-        {
-            var series = _libraryManager.GetItemList(new InternalItemsQuery
-            {
-                IncludeItemTypes = new[] { typeof(Series).Name },
-                DtoOptions = new DtoOptions(false)
-                {
-                    EnableImages = false
-                }
-
-            }).Where(i => string.Equals(request.TvdbId, i.GetProviderId(MetadataProvider.Tvdb), StringComparison.OrdinalIgnoreCase)).ToArray();
-
-            foreach (var item in series)
-            {
-                _libraryMonitor.ReportFileSystemChanged(item.Path);
-            }
-        }
-
-        public void Post(PostUpdatedMedia request)
-        {
-            if (request.Updates != null)
-            {
-                foreach (var item in request.Updates)
-                {
-                    _libraryMonitor.ReportFileSystemChanged(item.Path);
-                }
-            }
-        }
-
-        public void Post(PostUpdatedMovies request)
-        {
-            var movies = _libraryManager.GetItemList(new InternalItemsQuery
-            {
-                IncludeItemTypes = new[] { typeof(Movie).Name },
-                DtoOptions = new DtoOptions(false)
-                {
-                    EnableImages = false
-                }
-
-            });
-
-            if (!string.IsNullOrWhiteSpace(request.ImdbId))
-            {
-                movies = movies.Where(i => string.Equals(request.ImdbId, i.GetProviderId(MetadataProvider.Imdb), StringComparison.OrdinalIgnoreCase)).ToList();
-            }
-            else if (!string.IsNullOrWhiteSpace(request.TmdbId))
-            {
-                movies = movies.Where(i => string.Equals(request.TmdbId, i.GetProviderId(MetadataProvider.Tmdb), StringComparison.OrdinalIgnoreCase)).ToList();
-            }
-            else
-            {
-                movies = new List<BaseItem>();
-            }
-
-            foreach (var item in movies)
-            {
-                _libraryMonitor.ReportFileSystemChanged(item.Path);
-            }
-        }
-
-        public Task<object> Get(GetDownload request)
-        {
-            var item = _libraryManager.GetItemById(request.Id);
-            var auth = _authContext.GetAuthorizationInfo(Request);
-
-            var user = auth.User;
-
-            if (user != null)
-            {
-                if (!item.CanDownload(user))
-                {
-                    throw new ArgumentException("Item does not support downloading");
-                }
-            }
-            else
-            {
-                if (!item.CanDownload())
-                {
-                    throw new ArgumentException("Item does not support downloading");
-                }
-            }
-
-            var headers = new Dictionary<string, string>();
-
-            if (user != null)
-            {
-                LogDownload(item, user, auth);
-            }
-
-            var path = item.Path;
-
-            // Quotes are valid in linux. They'll possibly cause issues here
-            var filename = (Path.GetFileName(path) ?? string.Empty).Replace("\"", string.Empty);
-            if (!string.IsNullOrWhiteSpace(filename))
-            {
-                // Kestrel doesn't support non-ASCII characters in headers
-                if (Regex.IsMatch(filename, @"[^\p{IsBasicLatin}]"))
-                {
-                    // Manually encoding non-ASCII characters, following https://tools.ietf.org/html/rfc5987#section-3.2.2
-                    headers[HeaderNames.ContentDisposition] = "attachment; filename*=UTF-8''" + WebUtility.UrlEncode(filename);
-                }
-                else
-                {
-                    headers[HeaderNames.ContentDisposition] = "attachment; filename=\"" + filename + "\"";
-                }
-            }
-
-            return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
-            {
-                Path = path,
-                ResponseHeaders = headers
-            });
-        }
-
-        private void LogDownload(BaseItem item, User user, AuthorizationInfo auth)
-        {
-            try
-            {
-                _activityManager.Create(new ActivityLog(
-                    string.Format(_localization.GetLocalizedString("UserDownloadingItemWithValues"), user.Username, item.Name),
-                    "UserDownloadingContent",
-                    auth.UserId)
-                {
-                    ShortOverview = string.Format(_localization.GetLocalizedString("AppDeviceValues"), auth.Client, auth.Device),
-                });
-            }
-            catch
-            {
-                // Logged at lower levels
-            }
-        }
-
-        public Task<object> Get(GetFile request)
-        {
-            var item = _libraryManager.GetItemById(request.Id);
-
-            return ResultFactory.GetStaticFileResult(Request, item.Path);
-        }
-
-        /// <summary>
-        /// Gets the specified request.
-        /// </summary>
-        /// <param name="request">The request.</param>
-        /// <returns>System.Object.</returns>
-        public object Get(GetPhyscialPaths request)
-        {
-            var result = _libraryManager.RootFolder.Children
-                .SelectMany(c => c.PhysicalLocations)
-                .ToList();
-
-            return ToOptimizedResult(result);
-        }
-
-        /// <summary>
-        /// Gets the specified request.
-        /// </summary>
-        /// <param name="request">The request.</param>
-        /// <returns>System.Object.</returns>
-        public object Get(GetAncestors request)
-        {
-            var result = GetAncestors(request);
-
-            return ToOptimizedResult(result);
-        }
-
-        /// <summary>
-        /// Gets the ancestors.
-        /// </summary>
-        /// <param name="request">The request.</param>
-        /// <returns>Task{BaseItemDto[]}.</returns>
-        public List<BaseItemDto> GetAncestors(GetAncestors request)
-        {
-            var item = _libraryManager.GetItemById(request.Id);
-
-            var baseItemDtos = new List<BaseItemDto>();
-
-            var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
-            var dtoOptions = GetDtoOptions(_authContext, request);
-
-            BaseItem parent = item.GetParent();
-
-            while (parent != null)
-            {
-                if (user != null)
-                {
-                    parent = TranslateParentItem(parent, user);
-                }
-
-                baseItemDtos.Add(_dtoService.GetBaseItemDto(parent, dtoOptions, user));
-
-                parent = parent.GetParent();
-            }
-
-            return baseItemDtos;
-        }
-
-        private BaseItem TranslateParentItem(BaseItem item, User user)
-        {
-            return item.GetParent() is AggregateFolder
-                ? _libraryManager.GetUserRootFolder().GetChildren(user, true)
-                    .FirstOrDefault(i => i.PhysicalLocations.Contains(item.Path))
-                : item;
-        }
-
-        /// <summary>
-        /// Gets the specified request.
-        /// </summary>
-        /// <param name="request">The request.</param>
-        /// <returns>System.Object.</returns>
-        public object Get(GetCriticReviews request)
-        {
-            return new QueryResult<BaseItemDto>();
-        }
-
-        /// <summary>
-        /// Gets the specified request.
-        /// </summary>
-        /// <param name="request">The request.</param>
-        /// <returns>System.Object.</returns>
-        public object Get(GetItemCounts request)
-        {
-            var user = request.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(request.UserId);
-
-            var counts = new ItemCounts
-            {
-                AlbumCount = GetCount(typeof(MusicAlbum), user, request),
-                EpisodeCount = GetCount(typeof(Episode), user, request),
-                MovieCount = GetCount(typeof(Movie), user, request),
-                SeriesCount = GetCount(typeof(Series), user, request),
-                SongCount = GetCount(typeof(Audio), user, request),
-                MusicVideoCount = GetCount(typeof(MusicVideo), user, request),
-                BoxSetCount = GetCount(typeof(BoxSet), user, request),
-                BookCount = GetCount(typeof(Book), user, request)
-            };
-
-            return ToOptimizedResult(counts);
-        }
-
-        private int GetCount(Type type, User user, GetItemCounts request)
-        {
-            var query = new InternalItemsQuery(user)
-            {
-                IncludeItemTypes = new[] { type.Name },
-                Limit = 0,
-                Recursive = true,
-                IsVirtualItem = false,
-                IsFavorite = request.IsFavorite,
-                DtoOptions = new DtoOptions(false)
-                {
-                    EnableImages = false
-                }
-            };
-
-            return _libraryManager.GetItemsResult(query).TotalRecordCount;
-        }
-
-        /// <summary>
-        /// Posts the specified request.
-        /// </summary>
-        /// <param name="request">The request.</param>
-        public async Task Post(RefreshLibrary request)
-        {
-            try
-            {
-                await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
-            }
-            catch (Exception ex)
-            {
-                Logger.LogError(ex, "Error refreshing library");
-            }
-        }
-
-        /// <summary>
-        /// Deletes the specified request.
-        /// </summary>
-        /// <param name="request">The request.</param>
-        public void Delete(DeleteItems request)
-        {
-            var ids = string.IsNullOrWhiteSpace(request.Ids)
-                ? Array.Empty<string>()
-                : request.Ids.Split(',');
-
-            foreach (var i in ids)
-            {
-                var item = _libraryManager.GetItemById(i);
-                var auth = _authContext.GetAuthorizationInfo(Request);
-                var user = auth.User;
-
-                if (!item.CanDelete(user))
-                {
-                    if (ids.Length > 1)
-                    {
-                        throw new SecurityException("Unauthorized access");
-                    }
-
-                    continue;
-                }
-
-                _libraryManager.DeleteItem(item, new DeleteOptions
-                {
-                    DeleteFileLocation = true
-                }, true);
-            }
-        }
-
-        /// <summary>
-        /// Deletes the specified request.
-        /// </summary>
-        /// <param name="request">The request.</param>
-        public void Delete(DeleteItem request)
-        {
-            Delete(new DeleteItems
-            {
-                Ids = request.Id
-            });
-        }
-
-        public object Get(GetThemeMedia request)
-        {
-            var themeSongs = GetThemeSongs(new GetThemeSongs
-            {
-                InheritFromParent = request.InheritFromParent,
-                Id = request.Id,
-                UserId = request.UserId
-
-            });
-
-            var themeVideos = GetThemeVideos(new GetThemeVideos
-            {
-                InheritFromParent = request.InheritFromParent,
-                Id = request.Id,
-                UserId = request.UserId
-
-            });
-
-            return ToOptimizedResult(new AllThemeMediaResult
-            {
-                ThemeSongsResult = themeSongs,
-                ThemeVideosResult = themeVideos,
-
-                SoundtrackSongsResult = new ThemeMediaResult()
-            });
-        }
-
-        /// <summary>
-        /// Gets the specified request.
-        /// </summary>
-        /// <param name="request">The request.</param>
-        /// <returns>System.Object.</returns>
-        public object Get(GetThemeSongs request)
-        {
-            var result = GetThemeSongs(request);
-
-            return ToOptimizedResult(result);
-        }
-
-        private ThemeMediaResult GetThemeSongs(GetThemeSongs request)
-        {
-            var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
-            var item = string.IsNullOrEmpty(request.Id)
-                           ? (!request.UserId.Equals(Guid.Empty)
-                                  ? _libraryManager.GetUserRootFolder()
-                                  : _libraryManager.RootFolder)
-                           : _libraryManager.GetItemById(request.Id);
-
-            if (item == null)
-            {
-                throw new ResourceNotFoundException("Item not found.");
-            }
-
-            IEnumerable<BaseItem> themeItems;
-
-            while (true)
-            {
-                themeItems = item.GetThemeSongs();
-
-                if (themeItems.Any() || !request.InheritFromParent)
-                {
-                    break;
-                }
-
-                var parent = item.GetParent();
-                if (parent == null)
-                {
-                    break;
-                }
-                item = parent;
-            }
-
-            var dtoOptions = GetDtoOptions(_authContext, request);
-            var items = themeItems
-                .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item))
-                .ToArray();
-
-            return new ThemeMediaResult
-            {
-                Items = items,
-                TotalRecordCount = items.Length,
-                OwnerId = item.Id
-            };
-        }
-
-        /// <summary>
-        /// Gets the specified request.
-        /// </summary>
-        /// <param name="request">The request.</param>
-        /// <returns>System.Object.</returns>
-        public object Get(GetThemeVideos request)
-        {
-            return ToOptimizedResult(GetThemeVideos(request));
-        }
-
-        public ThemeMediaResult GetThemeVideos(GetThemeVideos request)
-        {
-            var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null;
-
-            var item = string.IsNullOrEmpty(request.Id)
-                           ? (!request.UserId.Equals(Guid.Empty)
-                                  ? _libraryManager.GetUserRootFolder()
-                                  : _libraryManager.RootFolder)
-                           : _libraryManager.GetItemById(request.Id);
-
-            if (item == null)
-            {
-                throw new ResourceNotFoundException("Item not found.");
-            }
-
-            IEnumerable<BaseItem> themeItems;
-
-            while (true)
-            {
-                themeItems = item.GetThemeVideos();
-
-                if (themeItems.Any() || !request.InheritFromParent)
-                {
-                    break;
-                }
-
-                var parent = item.GetParent();
-                if (parent == null)
-                {
-                    break;
-                }
-                item = parent;
-            }
-
-            var dtoOptions = GetDtoOptions(_authContext, request);
-
-            var items = themeItems
-                .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item))
-                .ToArray();
-
-            return new ThemeMediaResult
-            {
-                Items = items,
-                TotalRecordCount = items.Length,
-                OwnerId = item.Id
-            };
-        }
-    }
-}

+ 4 - 0
MediaBrowser.Api/MediaBrowser.Api.csproj

@@ -14,6 +14,10 @@
     <Compile Include="..\SharedVersion.cs" />
   </ItemGroup>
 
+  <ItemGroup>
+    <Folder Include="Library" />
+  </ItemGroup>
+
   <PropertyGroup>
     <TargetFramework>netstandard2.1</TargetFramework>
     <GenerateAssemblyInfo>false</GenerateAssemblyInfo>