2
0

PlaylistsController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 Jellyfin.Data.Enums;
  12. using Jellyfin.Extensions;
  13. using MediaBrowser.Controller.Dto;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Playlists;
  16. using MediaBrowser.Model.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.Playlists;
  19. using MediaBrowser.Model.Querying;
  20. using Microsoft.AspNetCore.Authorization;
  21. using Microsoft.AspNetCore.Http;
  22. using Microsoft.AspNetCore.Mvc;
  23. using Microsoft.AspNetCore.Mvc.ModelBinding;
  24. namespace Jellyfin.Api.Controllers;
  25. /// <summary>
  26. /// Playlists controller.
  27. /// </summary>
  28. [Authorize]
  29. public class PlaylistsController : BaseJellyfinApiController
  30. {
  31. private readonly IPlaylistManager _playlistManager;
  32. private readonly IDtoService _dtoService;
  33. private readonly IUserManager _userManager;
  34. private readonly ILibraryManager _libraryManager;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="PlaylistsController"/> class.
  37. /// </summary>
  38. /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
  39. /// <param name="playlistManager">Instance of the <see cref="IPlaylistManager"/> interface.</param>
  40. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  41. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  42. public PlaylistsController(
  43. IDtoService dtoService,
  44. IPlaylistManager playlistManager,
  45. IUserManager userManager,
  46. ILibraryManager libraryManager)
  47. {
  48. _dtoService = dtoService;
  49. _playlistManager = playlistManager;
  50. _userManager = userManager;
  51. _libraryManager = libraryManager;
  52. }
  53. /// <summary>
  54. /// Creates a new playlist.
  55. /// </summary>
  56. /// <remarks>
  57. /// For backwards compatibility parameters can be sent via Query or Body, with Query having higher precedence.
  58. /// Query parameters are obsolete.
  59. /// </remarks>
  60. /// <param name="name">The playlist name.</param>
  61. /// <param name="ids">The item ids.</param>
  62. /// <param name="userId">The user id.</param>
  63. /// <param name="mediaType">The media type.</param>
  64. /// <param name="createPlaylistRequest">The create playlist payload.</param>
  65. /// <response code="200">Playlist created.</response>
  66. /// <returns>
  67. /// A <see cref="Task" /> that represents the asynchronous operation to create a playlist.
  68. /// The task result contains an <see cref="OkResult"/> indicating success.
  69. /// </returns>
  70. [HttpPost]
  71. [ProducesResponseType(StatusCodes.Status200OK)]
  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] MediaType? 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. /// Get a playlist's shares.
  96. /// </summary>
  97. /// <param name="playlistId">The playlist id.</param>
  98. /// <returns>
  99. /// A list of <see cref="Share"/> objects.
  100. /// </returns>
  101. [HttpGet("{playlistId}/Shares")]
  102. [ProducesResponseType(StatusCodes.Status200OK)]
  103. public IReadOnlyList<Share> GetPlaylistShares(
  104. [FromRoute, Required] Guid playlistId)
  105. {
  106. var userId = RequestHelpers.GetUserId(User, default);
  107. var playlist = _playlistManager.GetPlaylist(userId, playlistId);
  108. var isPermitted = playlist.OwnerUserId.Equals(userId)
  109. || playlist.Shares.Any(s => s.CanEdit && (s.UserId?.Equals(userId) ?? false));
  110. return isPermitted ? playlist.Shares : new List<Share>();
  111. }
  112. /// <summary>
  113. /// Toggles OpenAccess of a playlist.
  114. /// </summary>
  115. /// <param name="playlistId">The playlist id.</param>
  116. /// <returns>
  117. /// A <see cref="Task" /> that represents the asynchronous operation to toggle OpenAccess of a playlist.
  118. /// The task result contains an <see cref="OkResult"/> indicating success.
  119. /// </returns>
  120. [HttpPost("{playlistId}/ToggleOpenAccess")]
  121. [ProducesResponseType(StatusCodes.Status200OK)]
  122. public async Task<ActionResult> ToggleopenAccess(
  123. [FromRoute, Required] Guid playlistId)
  124. {
  125. var callingUserId = RequestHelpers.GetUserId(User, default);
  126. var playlist = _playlistManager.GetPlaylist(callingUserId, playlistId);
  127. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  128. || playlist.Shares.Any(s => s.CanEdit && (s.UserId?.Equals(callingUserId) ?? false));
  129. if (!isPermitted)
  130. {
  131. return Unauthorized("Unauthorized access");
  132. }
  133. await _playlistManager.ToggleOpenAccess(playlistId, callingUserId).ConfigureAwait(false);
  134. return NoContent();
  135. }
  136. /// <summary>
  137. /// Adds shares to a playlist's shares.
  138. /// </summary>
  139. /// <param name="playlistId">The playlist id.</param>
  140. /// <param name="shares">The shares.</param>
  141. /// <returns>
  142. /// A <see cref="Task" /> that represents the asynchronous operation to add shares to a playlist.
  143. /// The task result contains an <see cref="OkResult"/> indicating success.
  144. /// </returns>
  145. [HttpPost("{playlistId}/Shares")]
  146. [ProducesResponseType(StatusCodes.Status200OK)]
  147. public async Task<ActionResult> AddUserToPlaylistShares(
  148. [FromRoute, Required] Guid playlistId,
  149. [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Disallow)] Share[] shares)
  150. {
  151. var callingUserId = RequestHelpers.GetUserId(User, default);
  152. var playlist = _playlistManager.GetPlaylist(callingUserId, playlistId);
  153. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  154. || playlist.Shares.Any(s => s.CanEdit && (s.UserId?.Equals(callingUserId) ?? false));
  155. if (!isPermitted)
  156. {
  157. return Unauthorized("Unauthorized access");
  158. }
  159. foreach (var share in shares)
  160. {
  161. await _playlistManager.AddToShares(playlistId, callingUserId, share).ConfigureAwait(false);
  162. }
  163. return NoContent();
  164. }
  165. /// <summary>
  166. /// Remove a user from a playlist's shares.
  167. /// </summary>
  168. /// <param name="playlistId">The playlist id.</param>
  169. /// <param name="userId">The user id.</param>
  170. /// <returns>
  171. /// A <see cref="Task" /> that represents the asynchronous operation to delete a user from a playlist's shares.
  172. /// The task result contains an <see cref="OkResult"/> indicating success.
  173. /// </returns>
  174. [HttpDelete("{playlistId}/Shares")]
  175. [ProducesResponseType(StatusCodes.Status200OK)]
  176. public async Task<ActionResult> RemoveUserFromPlaylistShares(
  177. [FromRoute, Required] Guid playlistId,
  178. [FromBody] Guid userId)
  179. {
  180. var callingUserId = RequestHelpers.GetUserId(User, default);
  181. var playlist = _playlistManager.GetPlaylist(callingUserId, playlistId);
  182. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  183. || playlist.Shares.Any(s => s.CanEdit && (s.UserId?.Equals(callingUserId) ?? false));
  184. if (!isPermitted)
  185. {
  186. return Unauthorized("Unauthorized access");
  187. }
  188. var share = playlist.Shares.FirstOrDefault(s => s.UserId?.Equals(userId) ?? false);
  189. if (share is null)
  190. {
  191. return NotFound();
  192. }
  193. await _playlistManager.RemoveFromShares(playlistId, callingUserId, share).ConfigureAwait(false);
  194. return NoContent();
  195. }
  196. /// <summary>
  197. /// Adds items to a playlist.
  198. /// </summary>
  199. /// <param name="playlistId">The playlist id.</param>
  200. /// <param name="ids">Item id, comma delimited.</param>
  201. /// <param name="userId">The userId.</param>
  202. /// <response code="204">Items added to playlist.</response>
  203. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  204. [HttpPost("{playlistId}/Items")]
  205. [ProducesResponseType(StatusCodes.Status204NoContent)]
  206. public async Task<ActionResult> AddToPlaylist(
  207. [FromRoute, Required] Guid playlistId,
  208. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
  209. [FromQuery] Guid? userId)
  210. {
  211. userId = RequestHelpers.GetUserId(User, userId);
  212. await _playlistManager.AddToPlaylistAsync(playlistId, ids, userId.Value).ConfigureAwait(false);
  213. return NoContent();
  214. }
  215. /// <summary>
  216. /// Moves a playlist item.
  217. /// </summary>
  218. /// <param name="playlistId">The playlist id.</param>
  219. /// <param name="itemId">The item id.</param>
  220. /// <param name="newIndex">The new index.</param>
  221. /// <response code="204">Item moved to new index.</response>
  222. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  223. [HttpPost("{playlistId}/Items/{itemId}/Move/{newIndex}")]
  224. [ProducesResponseType(StatusCodes.Status204NoContent)]
  225. public async Task<ActionResult> MoveItem(
  226. [FromRoute, Required] string playlistId,
  227. [FromRoute, Required] string itemId,
  228. [FromRoute, Required] int newIndex)
  229. {
  230. await _playlistManager.MoveItemAsync(playlistId, itemId, newIndex).ConfigureAwait(false);
  231. return NoContent();
  232. }
  233. /// <summary>
  234. /// Removes items from a playlist.
  235. /// </summary>
  236. /// <param name="playlistId">The playlist id.</param>
  237. /// <param name="entryIds">The item ids, comma delimited.</param>
  238. /// <response code="204">Items removed.</response>
  239. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  240. [HttpDelete("{playlistId}/Items")]
  241. [ProducesResponseType(StatusCodes.Status204NoContent)]
  242. public async Task<ActionResult> RemoveFromPlaylist(
  243. [FromRoute, Required] string playlistId,
  244. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] entryIds)
  245. {
  246. await _playlistManager.RemoveFromPlaylistAsync(playlistId, entryIds).ConfigureAwait(false);
  247. return NoContent();
  248. }
  249. /// <summary>
  250. /// Gets the original items of a playlist.
  251. /// </summary>
  252. /// <param name="playlistId">The playlist id.</param>
  253. /// <param name="userId">User id.</param>
  254. /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
  255. /// <param name="limit">Optional. The maximum number of records to return.</param>
  256. /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
  257. /// <param name="enableImages">Optional. Include image information in output.</param>
  258. /// <param name="enableUserData">Optional. Include user data.</param>
  259. /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
  260. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  261. /// <response code="200">Original playlist returned.</response>
  262. /// <response code="404">Playlist not found.</response>
  263. /// <returns>The original playlist items.</returns>
  264. [HttpGet("{playlistId}/Items")]
  265. [ProducesResponseType(StatusCodes.Status200OK)]
  266. [ProducesResponseType(StatusCodes.Status404NotFound)]
  267. public ActionResult<QueryResult<BaseItemDto>> GetPlaylistItems(
  268. [FromRoute, Required] Guid playlistId,
  269. [FromQuery] Guid? userId,
  270. [FromQuery] int? startIndex,
  271. [FromQuery] int? limit,
  272. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  273. [FromQuery] bool? enableImages,
  274. [FromQuery] bool? enableUserData,
  275. [FromQuery] int? imageTypeLimit,
  276. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
  277. {
  278. userId = RequestHelpers.GetUserId(User, userId);
  279. var playlist = (Playlist)_libraryManager.GetItemById(playlistId);
  280. if (playlist is null)
  281. {
  282. return NotFound();
  283. }
  284. var user = userId.IsNullOrEmpty()
  285. ? null
  286. : _userManager.GetUserById(userId.Value);
  287. var items = playlist.GetManageableItems().ToArray();
  288. var count = items.Length;
  289. if (startIndex.HasValue)
  290. {
  291. items = items.Skip(startIndex.Value).ToArray();
  292. }
  293. if (limit.HasValue)
  294. {
  295. items = items.Take(limit.Value).ToArray();
  296. }
  297. var dtoOptions = new DtoOptions { Fields = fields }
  298. .AddClientFields(User)
  299. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  300. var dtos = _dtoService.GetBaseItemDtos(items.Select(i => i.Item2).ToList(), dtoOptions, user);
  301. for (int index = 0; index < dtos.Count; index++)
  302. {
  303. dtos[index].PlaylistItemId = items[index].Item1.Id;
  304. }
  305. var result = new QueryResult<BaseItemDto>(
  306. startIndex,
  307. count,
  308. dtos);
  309. return result;
  310. }
  311. }