jellyfin/Jellyfin.Api/Controllers/LibraryController.cs

1004 lines
41 KiB
C#
Raw Normal View History

2020-06-19 12:10:10 -07:00
using System;
using System.Collections.Generic;
2020-08-06 07:17:45 -07:00
using System.ComponentModel.DataAnnotations;
2020-06-19 12:10:10 -07:00
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.Attributes;
2020-06-19 12:10:10 -07:00
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
2020-11-09 14:59:04 -07:00
using Jellyfin.Api.ModelBinders;
2020-06-19 12:10:10 -07:00
using Jellyfin.Api.Models.LibraryDtos;
using Jellyfin.Data.Entities;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Configuration;
2020-04-25 17:18:33 -07:00
using MediaBrowser.Controller.Dto;
2020-06-19 12:10:10 -07:00
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
2020-08-29 10:30:09 -07:00
using MediaBrowser.Controller.Entities.TV;
2020-04-25 17:18:33 -07:00
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
2020-04-25 17:18:33 -07:00
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Activity;
2020-06-19 12:10:10 -07:00
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
2020-04-25 17:18:33 -07:00
using MediaBrowser.Model.Globalization;
2020-06-19 12:10:10 -07:00
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
2020-06-24 07:01:12 -07:00
using Microsoft.AspNetCore.Http;
2020-04-25 17:18:33 -07:00
using Microsoft.AspNetCore.Mvc;
2020-06-19 12:10:10 -07:00
using Microsoft.Extensions.Logging;
using Book = MediaBrowser.Controller.Entities.Book;
2020-04-25 17:18:33 -07:00
namespace Jellyfin.Api.Controllers
{
/// <summary>
/// Library Controller.
/// </summary>
2020-08-04 11:48:53 -07:00
[Route("")]
2020-04-25 17:18:33 -07:00
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;
2020-06-19 12:10:10 -07:00
private readonly ILogger<LibraryController> _logger;
private readonly IServerConfigurationManager _serverConfigurationManager;
2020-04-25 17:18:33 -07:00
/// <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>
2020-06-19 12:10:10 -07:00
/// <param name="logger">Instance of the <see cref="ILogger{LibraryController}"/> interface.</param>
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
2020-04-25 17:18:33 -07:00
public LibraryController(
IProviderManager providerManager,
ILibraryManager libraryManager,
IUserManager userManager,
IDtoService dtoService,
IAuthorizationContext authContext,
IActivityManager activityManager,
ILocalizationManager localization,
2020-06-19 12:10:10 -07:00
ILibraryMonitor libraryMonitor,
ILogger<LibraryController> logger,
IServerConfigurationManager serverConfigurationManager)
2020-04-25 17:18:33 -07:00
{
_providerManager = providerManager;
_libraryManager = libraryManager;
_userManager = userManager;
_dtoService = dtoService;
_authContext = authContext;
_activityManager = activityManager;
_localization = localization;
_libraryMonitor = libraryMonitor;
2020-06-19 12:10:10 -07:00
_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>
2020-08-04 11:48:53 -07:00
[HttpGet("Items/{itemId}/File")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesFile("video/*", "audio/*")]
2020-09-06 08:07:27 -07:00
public ActionResult GetFile([FromRoute, Required] Guid itemId)
2020-06-19 12:10:10 -07:00
{
var item = _libraryManager.GetItemById(itemId);
if (item == null)
{
return NotFound();
}
return PhysicalFile(item.Path, MimeTypes.GetMimeType(item.Path), true);
2020-06-19 12:10:10 -07:00
}
/// <summary>
/// Gets critic review for an item.
/// </summary>
/// <response code="200">Critic reviews returned.</response>
/// <returns>The list of critic reviews.</returns>
2020-08-04 11:48:53 -07:00
[HttpGet("Items/{itemId}/CriticReviews")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
[Obsolete("This endpoint is obsolete.")]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-06-24 13:43:28 -07:00
public ActionResult<QueryResult<BaseItemDto>> GetCriticReviews()
2020-06-19 12:10:10 -07:00
{
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>
2020-08-04 11:48:53 -07:00
[HttpGet("Items/{itemId}/ThemeSongs")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
2020-06-19 12:10:10 -07:00
public ActionResult<ThemeMediaResult> GetThemeSongs(
2020-09-06 08:07:27 -07:00
[FromRoute, Required] Guid itemId,
[FromQuery] Guid? userId,
[FromQuery] bool inheritFromParent = false)
2020-06-19 12:10:10 -07:00
{
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
2020-06-19 12:10:10 -07:00
: 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>
2020-08-04 11:48:53 -07:00
[HttpGet("Items/{itemId}/ThemeVideos")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
2020-06-19 12:10:10 -07:00
public ActionResult<ThemeMediaResult> GetThemeVideos(
2020-09-06 08:07:27 -07:00
[FromRoute, Required] Guid itemId,
[FromQuery] Guid? userId,
[FromQuery] bool inheritFromParent = false)
2020-06-19 12:10:10 -07:00
{
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
2020-06-19 12:10:10 -07:00
: 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>
2020-08-04 11:48:53 -07:00
[HttpGet("Items/{itemId}/ThemeMedia")]
2020-06-25 12:01:41 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-06-19 12:10:10 -07:00
public ActionResult<AllThemeMediaResult> GetThemeMedia(
2020-09-06 08:07:27 -07:00
[FromRoute, Required] Guid itemId,
[FromQuery] Guid? userId,
[FromQuery] bool inheritFromParent = false)
2020-06-19 12:10:10 -07:00
{
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>
[HttpPost("Library/Refresh")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.RequiresElevation)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
2020-06-19 12:10:10 -07:00
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>
2020-08-04 11:48:53 -07:00
[HttpDelete("Items/{itemId}")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
2021-05-20 20:56:59 -07:00
public async Task<ActionResult> DeleteItem(Guid itemId)
2020-06-19 12:10:10 -07:00
{
var item = _libraryManager.GetItemById(itemId);
2021-05-20 20:56:59 -07:00
var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
2020-06-19 12:10:10 -07:00
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>
2020-08-04 11:48:53 -07:00
[HttpDelete("Items")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
2021-05-20 20:56:59 -07:00
public async Task<ActionResult> DeleteItems([FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids)
2020-06-19 12:10:10 -07:00
{
if (ids.Length == 0)
{
return NoContent();
}
2020-06-19 12:10:10 -07:00
foreach (var i in ids)
2020-06-19 12:10:10 -07:00
{
var item = _libraryManager.GetItemById(i);
2021-05-20 20:56:59 -07:00
var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
2020-06-19 12:10:10 -07:00
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>
2020-08-04 11:48:53 -07:00
[HttpGet("Items/Counts")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-06-19 12:10:10 -07:00
public ActionResult<ItemCounts> GetItemCounts(
[FromQuery] Guid? userId,
2020-06-19 12:10:10 -07:00
[FromQuery] bool? isFavorite)
{
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
2020-06-19 12:10:10 -07:00
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>
2020-08-04 11:48:53 -07:00
[HttpGet("Items/{itemId}/Ancestors")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
2020-09-06 08:07:27 -07:00
public ActionResult<IEnumerable<BaseItemDto>> GetAncestors([FromRoute, Required] Guid itemId, [FromQuery] Guid? userId)
2020-06-19 12:10:10 -07:00
{
var item = _libraryManager.GetItemById(itemId);
if (item == null)
{
return NotFound("Item not found");
}
var baseItemDtos = new List<BaseItemDto>();
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
2020-06-19 12:10:10 -07:00
: null;
var dtoOptions = new DtoOptions().AddClientFields(Request);
BaseItem? parent = item.GetParent();
2020-06-19 12:10:10 -07:00
while (parent != null)
{
if (user != null)
{
parent = TranslateParentItem(parent, user);
}
baseItemDtos.Add(_dtoService.GetBaseItemDto(parent, dtoOptions, user));
parent = parent?.GetParent();
2020-06-19 12:10:10 -07:00
}
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>
2020-08-04 11:48:53 -07:00
[HttpGet("Library/PhysicalPaths")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.RequiresElevation)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-06-19 12:10:10 -07:00
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>
2020-06-24 07:01:12 -07:00
/// <response code="200">Media folders returned.</response>
2020-06-19 12:10:10 -07:00
/// <returns>List of user media folders.</returns>
2020-08-04 11:48:53 -07:00
[HttpGet("Library/MediaFolders")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-06-19 12:10:10 -07:00
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>
2020-08-04 11:48:53 -07:00
[HttpPost("Library/Series/Added", Name = "PostAddedSeries")]
[HttpPost("Library/Series/Updated")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
2020-06-27 09:50:44 -07:00
public ActionResult PostUpdatedSeries([FromQuery] string? tvdbId)
2020-06-19 12:10:10 -07:00
{
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>
2020-08-04 11:48:53 -07:00
[HttpPost("Library/Movies/Added", Name = "PostAddedMovies")]
[HttpPost("Library/Movies/Updated")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
2020-09-07 17:45:06 -07:00
public ActionResult PostUpdatedMovies([FromQuery] string? tmdbId, [FromQuery] string? imdbId)
2020-06-19 12:10:10 -07:00
{
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>
2021-03-11 22:45:58 -07:00
/// <param name="dto">The update paths.</param>
2020-06-19 12:10:10 -07:00
/// <response code="204">Report success.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
2020-08-04 11:48:53 -07:00
[HttpPost("Library/Media/Updated")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
2021-03-11 22:45:58 -07:00
public ActionResult PostUpdatedMedia([FromBody, Required] MediaUpdateInfoDto dto)
2020-06-19 12:10:10 -07:00
{
2021-03-11 22:45:58 -07:00
foreach (var item in dto.Updates)
2020-06-19 12:10:10 -07:00
{
_libraryMonitor.ReportFileSystemChanged(item.Path ?? throw new ArgumentException("Item path can't be null."));
2020-06-19 12:10:10 -07:00
}
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>
2020-08-04 11:48:53 -07:00
[HttpGet("Items/{itemId}/Download")]
2020-06-19 12:10:10 -07:00
[Authorize(Policy = Policies.Download)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesFile("video/*", "audio/*")]
2020-09-06 08:07:27 -07:00
public async Task<ActionResult> GetDownload([FromRoute, Required] Guid itemId)
2020-06-19 12:10:10 -07:00
{
var item = _libraryManager.GetItemById(itemId);
if (item == null)
{
return NotFound();
}
2021-05-20 20:56:59 -07:00
var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);
2020-06-19 12:10:10 -07:00
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)
{
await LogDownloadAsync(item, user, auth).ConfigureAwait(false);
2020-06-19 12:10:10 -07:00
}
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.
return PhysicalFile(path, MimeTypes.GetMimeType(path), filename, true);
2020-06-19 12:10:10 -07:00
}
/// <summary>
/// Gets similar items.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <param name="excludeArtistIds">Exclude artist ids.</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>
2020-06-24 07:01:12 -07:00
/// <response code="200">Similar items returned.</response>
2020-06-19 12:10:10 -07:00
/// <returns>A <see cref="QueryResult{BaseItemDto}"/> containing the similar items.</returns>
[HttpGet("Artists/{itemId}/Similar", Name = "GetSimilarArtists")]
2020-08-04 11:48:53 -07:00
[HttpGet("Items/{itemId}/Similar")]
[HttpGet("Albums/{itemId}/Similar", Name = "GetSimilarAlbums")]
[HttpGet("Shows/{itemId}/Similar", Name = "GetSimilarShows")]
[HttpGet("Movies/{itemId}/Similar", Name = "GetSimilarMovies")]
[HttpGet("Trailers/{itemId}/Similar", Name = "GetSimilarTrailers")]
2020-08-06 07:17:45 -07:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-06-19 12:10:10 -07:00
public ActionResult<QueryResult<BaseItemDto>> GetSimilarItems(
2020-09-06 08:07:27 -07:00
[FromRoute, Required] Guid itemId,
[FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
[FromQuery] Guid? userId,
2020-06-19 12:10:10 -07:00
[FromQuery] int? limit,
2020-11-09 14:59:04 -07:00
[FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields)
2020-06-19 12:10:10 -07:00
{
var item = itemId.Equals(Guid.Empty)
? (!userId.Equals(Guid.Empty)
? _libraryManager.GetUserRootFolder()
: _libraryManager.RootFolder)
: _libraryManager.GetItemById(itemId);
2021-08-28 15:32:50 -07:00
if (item is Episode || (item is IItemByName && item is not MusicArtist))
{
return new QueryResult<BaseItemDto>();
}
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request);
2020-06-19 12:10:10 -07:00
var program = item as IHasProgramAttributes;
bool? isMovie = item is Movie || (program != null && program.IsMovie) || item is Trailer;
bool? isSeries = item is Series || (program != null && program.IsSeries);
var includeItemTypes = new List<string>();
if (isMovie.Value)
2020-06-19 12:10:10 -07:00
{
includeItemTypes.Add(nameof(Movie));
if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
{
includeItemTypes.Add(nameof(Trailer));
includeItemTypes.Add(nameof(LiveTvProgram));
}
}
else if (isSeries.Value)
{
includeItemTypes.Add(nameof(Series));
}
else
{
2020-12-20 09:00:27 -07:00
// For non series and movie types these columns are typically null
isSeries = null;
isMovie = null;
includeItemTypes.Add(item.GetType().Name);
2020-06-19 12:10:10 -07:00
}
var query = new InternalItemsQuery(user)
2020-06-19 12:10:10 -07:00
{
Limit = limit,
IncludeItemTypes = includeItemTypes.ToArray(),
SimilarTo = item,
DtoOptions = dtoOptions,
EnableTotalRecordCount = !isMovie ?? true,
EnableGroupByMetadataKey = isMovie ?? false,
MinSimilarityScore = 2 // A remnant from album/artist scoring
};
// ExcludeArtistIds
if (excludeArtistIds.Length != 0)
{
query.ExcludeArtistIds = excludeArtistIds;
2020-06-19 12:10:10 -07:00
}
List<BaseItem> itemsResult = _libraryManager.GetItemList(query);
var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);
return new QueryResult<BaseItemDto>
{
Items = returnList,
TotalRecordCount = itemsResult.Count
};
2020-06-19 12:10:10 -07:00
}
/// <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>
2020-08-04 11:48:53 -07:00
[HttpGet("Libraries/AvailableOptions")]
2020-08-06 07:17:45 -07:00
[Authorize(Policy = Policies.FirstTimeSetupOrDefault)]
2020-06-24 07:01:12 -07:00
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<LibraryOptionsResultDto> GetLibraryOptionsInfo(
[FromQuery] string? libraryContentType,
[FromQuery] bool isNewLibrary = false)
2020-06-19 12:10:10 -07:00
{
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)
2020-06-19 12:10:10 -07:00
{
return item.GetParent() is AggregateFolder
? _libraryManager.GetUserRootFolder().GetChildren(user, true)
.FirstOrDefault(i => i.PhysicalLocations.Contains(item.Path))
: item;
}
private async Task LogDownloadAsync(BaseItem item, User user, AuthorizationInfo auth)
2020-06-19 12:10:10 -07:00
{
try
{
await _activityManager.CreateAsync(new ActivityLog(
2020-06-19 12:10:10 -07:00
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),
}).ConfigureAwait(false);
2020-06-19 12:10:10 -07:00
}
catch
{
// Logged at lower levels
}
}
2020-06-27 09:50:44 -07:00
private static string[] GetRepresentativeItemTypes(string? contentType)
2020-06-19 12:10:10 -07:00
{
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));
2020-04-25 17:18:33 -07:00
}
}
}