PlaylistsController.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Api.Attributes;
  7. using Jellyfin.Api.Extensions;
  8. using Jellyfin.Api.Helpers;
  9. using Jellyfin.Api.ModelBinders;
  10. using Jellyfin.Api.Models.PlaylistDtos;
  11. using MediaBrowser.Controller.Dto;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.Playlists;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.Playlists;
  17. using MediaBrowser.Model.Querying;
  18. using Microsoft.AspNetCore.Authorization;
  19. using Microsoft.AspNetCore.Http;
  20. using Microsoft.AspNetCore.Mvc;
  21. using Microsoft.AspNetCore.Mvc.ModelBinding;
  22. namespace Jellyfin.Api.Controllers;
  23. /// <summary>
  24. /// Playlists controller.
  25. /// </summary>
  26. [Authorize]
  27. public class PlaylistsController : BaseJellyfinApiController
  28. {
  29. private readonly IPlaylistManager _playlistManager;
  30. private readonly IDtoService _dtoService;
  31. private readonly IUserManager _userManager;
  32. private readonly ILibraryManager _libraryManager;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="PlaylistsController"/> class.
  35. /// </summary>
  36. /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
  37. /// <param name="playlistManager">Instance of the <see cref="IPlaylistManager"/> interface.</param>
  38. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  39. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  40. public PlaylistsController(
  41. IDtoService dtoService,
  42. IPlaylistManager playlistManager,
  43. IUserManager userManager,
  44. ILibraryManager libraryManager)
  45. {
  46. _dtoService = dtoService;
  47. _playlistManager = playlistManager;
  48. _userManager = userManager;
  49. _libraryManager = libraryManager;
  50. }
  51. /// <summary>
  52. /// Creates a new playlist.
  53. /// </summary>
  54. /// <remarks>
  55. /// For backwards compatibility parameters can be sent via Query or Body, with Query having higher precedence.
  56. /// Query parameters are obsolete.
  57. /// </remarks>
  58. /// <param name="name">The playlist name.</param>
  59. /// <param name="ids">The item ids.</param>
  60. /// <param name="userId">The user id.</param>
  61. /// <param name="mediaType">The media type.</param>
  62. /// <param name="createPlaylistRequest">The create playlist payload.</param>
  63. /// <response code="200">Playlist created.</response>
  64. /// <response code="403">User does not have permission to create playlists.</response>
  65. /// <returns>
  66. /// A <see cref="Task" /> that represents the asynchronous operation to create a playlist.
  67. /// The task result contains an <see cref="OkResult"/> indicating success.
  68. /// </returns>
  69. [HttpPost]
  70. [ProducesResponseType(StatusCodes.Status200OK)]
  71. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  72. public async Task<ActionResult<PlaylistCreationResult>> CreatePlaylist(
  73. [FromQuery, ParameterObsolete] string? name,
  74. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder)), ParameterObsolete] IReadOnlyList<Guid> ids,
  75. [FromQuery, ParameterObsolete] Guid? userId,
  76. [FromQuery, ParameterObsolete] string? mediaType,
  77. [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] CreatePlaylistDto? createPlaylistRequest)
  78. {
  79. if (ids.Count == 0)
  80. {
  81. ids = createPlaylistRequest?.Ids ?? Array.Empty<Guid>();
  82. }
  83. userId ??= createPlaylistRequest?.UserId ?? default;
  84. userId = RequestHelpers.GetUserId(User, userId);
  85. var result = await _playlistManager.CreatePlaylist(new PlaylistCreationRequest
  86. {
  87. Name = name ?? createPlaylistRequest?.Name,
  88. ItemIdList = ids,
  89. UserId = userId.Value,
  90. MediaType = mediaType ?? createPlaylistRequest?.MediaType
  91. }).ConfigureAwait(false);
  92. return result;
  93. }
  94. /// <summary>
  95. /// Adds items to a playlist.
  96. /// </summary>
  97. /// <param name="playlistId">The playlist id.</param>
  98. /// <param name="ids">Item id, comma delimited.</param>
  99. /// <param name="userId">The userId.</param>
  100. /// <response code="204">Items added to playlist.</response>
  101. /// <response code="403">User does not have permission to add items to playlist.</response>
  102. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  103. [HttpPost("{playlistId}/Items")]
  104. [ProducesResponseType(StatusCodes.Status204NoContent)]
  105. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  106. public async Task<ActionResult> AddToPlaylist(
  107. [FromRoute, Required] Guid playlistId,
  108. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
  109. [FromQuery] Guid? userId)
  110. {
  111. userId = RequestHelpers.GetUserId(User, userId);
  112. await _playlistManager.AddToPlaylistAsync(playlistId, ids, userId.Value).ConfigureAwait(false);
  113. return NoContent();
  114. }
  115. /// <summary>
  116. /// Moves a playlist item.
  117. /// </summary>
  118. /// <param name="playlistId">The playlist id.</param>
  119. /// <param name="itemId">The item id.</param>
  120. /// <param name="newIndex">The new index.</param>
  121. /// <response code="204">Item moved to new index.</response>
  122. /// <response code="403">User does not have permission to move item.</response>
  123. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  124. [HttpPost("{playlistId}/Items/{itemId}/Move/{newIndex}")]
  125. [ProducesResponseType(StatusCodes.Status204NoContent)]
  126. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  127. public async Task<ActionResult> MoveItem(
  128. [FromRoute, Required] string playlistId,
  129. [FromRoute, Required] string itemId,
  130. [FromRoute, Required] int newIndex)
  131. {
  132. await _playlistManager.MoveItemAsync(playlistId, itemId, newIndex).ConfigureAwait(false);
  133. return NoContent();
  134. }
  135. /// <summary>
  136. /// Removes items from a playlist.
  137. /// </summary>
  138. /// <param name="playlistId">The playlist id.</param>
  139. /// <param name="entryIds">The item ids, comma delimited.</param>
  140. /// <response code="204">Items removed.</response>
  141. /// <response code="403">User does not have permission to get playlist.</response>
  142. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  143. [HttpDelete("{playlistId}/Items")]
  144. [ProducesResponseType(StatusCodes.Status204NoContent)]
  145. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  146. public async Task<ActionResult> RemoveFromPlaylist(
  147. [FromRoute, Required] string playlistId,
  148. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] entryIds)
  149. {
  150. await _playlistManager.RemoveFromPlaylistAsync(playlistId, entryIds).ConfigureAwait(false);
  151. return NoContent();
  152. }
  153. /// <summary>
  154. /// Gets the original items of a playlist.
  155. /// </summary>
  156. /// <param name="playlistId">The playlist id.</param>
  157. /// <param name="userId">User id.</param>
  158. /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
  159. /// <param name="limit">Optional. The maximum number of records to return.</param>
  160. /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
  161. /// <param name="enableImages">Optional. Include image information in output.</param>
  162. /// <param name="enableUserData">Optional. Include user data.</param>
  163. /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
  164. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  165. /// <response code="200">Original playlist returned.</response>
  166. /// <response code="403">User does not have permission to get playlist items.</response>
  167. /// <response code="404">Playlist not found.</response>
  168. /// <returns>The original playlist items.</returns>
  169. [HttpGet("{playlistId}/Items")]
  170. [ProducesResponseType(StatusCodes.Status200OK)]
  171. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  172. [ProducesResponseType(StatusCodes.Status404NotFound)]
  173. public ActionResult<QueryResult<BaseItemDto>> GetPlaylistItems(
  174. [FromRoute, Required] Guid playlistId,
  175. [FromQuery, Required] Guid userId,
  176. [FromQuery] int? startIndex,
  177. [FromQuery] int? limit,
  178. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  179. [FromQuery] bool? enableImages,
  180. [FromQuery] bool? enableUserData,
  181. [FromQuery] int? imageTypeLimit,
  182. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
  183. {
  184. var playlist = (Playlist)_libraryManager.GetItemById(playlistId);
  185. if (playlist is null)
  186. {
  187. return NotFound();
  188. }
  189. var user = userId.Equals(default)
  190. ? null
  191. : _userManager.GetUserById(userId);
  192. var items = playlist.GetManageableItems().ToArray();
  193. var count = items.Length;
  194. if (startIndex.HasValue)
  195. {
  196. items = items.Skip(startIndex.Value).ToArray();
  197. }
  198. if (limit.HasValue)
  199. {
  200. items = items.Take(limit.Value).ToArray();
  201. }
  202. var dtoOptions = new DtoOptions { Fields = fields }
  203. .AddClientFields(User)
  204. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  205. var dtos = _dtoService.GetBaseItemDtos(items.Select(i => i.Item2).ToList(), dtoOptions, user);
  206. for (int index = 0; index < dtos.Count; index++)
  207. {
  208. dtos[index].PlaylistItemId = items[index].Item1.Id;
  209. }
  210. var result = new QueryResult<BaseItemDto>(
  211. startIndex,
  212. count,
  213. dtos);
  214. return result;
  215. }
  216. }