PlaylistsController.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. Users = createPlaylistRequest?.Users.ToArray() ?? [],
  92. Public = createPlaylistRequest?.Public
  93. }).ConfigureAwait(false);
  94. return result;
  95. }
  96. /// <summary>
  97. /// Get a playlist's users.
  98. /// </summary>
  99. /// <param name="playlistId">The playlist id.</param>
  100. /// <response code="200">Found shares.</response>
  101. /// <response code="401">Unauthorized access.</response>
  102. /// <response code="404">Playlist not found.</response>
  103. /// <returns>
  104. /// A list of <see cref="PlaylistUserPermissions"/> objects.
  105. /// </returns>
  106. [HttpGet("{playlistId}/User")]
  107. [ProducesResponseType(StatusCodes.Status200OK)]
  108. [ProducesResponseType(StatusCodes.Status401Unauthorized)]
  109. [ProducesResponseType(StatusCodes.Status404NotFound)]
  110. public ActionResult<IReadOnlyList<PlaylistUserPermissions>> GetPlaylistUsers(
  111. [FromRoute, Required] Guid playlistId)
  112. {
  113. var userId = User.GetUserId();
  114. var playlist = _playlistManager.GetPlaylist(userId, playlistId);
  115. if (playlist is null)
  116. {
  117. return NotFound("Playlist not found");
  118. }
  119. var isPermitted = playlist.OwnerUserId.Equals(userId)
  120. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(userId));
  121. return isPermitted ? playlist.Shares.ToList() : Unauthorized("Unauthorized Access");
  122. }
  123. /// <summary>
  124. /// Toggles public access of a playlist.
  125. /// </summary>
  126. /// <param name="playlistId">The playlist id.</param>
  127. /// <response code="204">Public access toggled.</response>
  128. /// <response code="401">Unauthorized access.</response>
  129. /// <response code="404">Playlist not found.</response>
  130. /// <returns>
  131. /// A <see cref="Task" /> that represents the asynchronous operation to toggle public access of a playlist.
  132. /// The task result contains an <see cref="OkResult"/> indicating success.
  133. /// </returns>
  134. [HttpPost("{playlistId}/TogglePublic")]
  135. [ProducesResponseType(StatusCodes.Status204NoContent)]
  136. [ProducesResponseType(StatusCodes.Status401Unauthorized)]
  137. public async Task<ActionResult> TogglePublicAccess(
  138. [FromRoute, Required] Guid playlistId)
  139. {
  140. var callingUserId = User.GetUserId();
  141. var playlist = _playlistManager.GetPlaylist(callingUserId, playlistId);
  142. if (playlist is null)
  143. {
  144. return NotFound("Playlist not found");
  145. }
  146. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  147. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  148. if (!isPermitted)
  149. {
  150. return Unauthorized("Unauthorized access");
  151. }
  152. await _playlistManager.ToggleOpenAccess(playlistId, callingUserId).ConfigureAwait(false);
  153. return NoContent();
  154. }
  155. /// <summary>
  156. /// Modify a user to a playlist's users.
  157. /// </summary>
  158. /// <param name="playlistId">The playlist id.</param>
  159. /// <param name="userId">The user id.</param>
  160. /// <param name="canEdit">Edit permission.</param>
  161. /// <response code="204">User's permissions modified.</response>
  162. /// <response code="401">Unauthorized access.</response>
  163. /// <response code="404">Playlist not found.</response>
  164. /// <returns>
  165. /// A <see cref="Task" /> that represents the asynchronous operation to modify an user's playlist permissions.
  166. /// The task result contains an <see cref="OkResult"/> indicating success.
  167. /// </returns>
  168. [HttpPost("{playlistId}/User/{userId}")]
  169. [ProducesResponseType(StatusCodes.Status204NoContent)]
  170. [ProducesResponseType(StatusCodes.Status401Unauthorized)]
  171. public async Task<ActionResult> ModifyPlaylistUserPermissions(
  172. [FromRoute, Required] Guid playlistId,
  173. [FromRoute, Required] Guid userId,
  174. [FromBody] bool canEdit)
  175. {
  176. var callingUserId = User.GetUserId();
  177. var playlist = _playlistManager.GetPlaylist(callingUserId, playlistId);
  178. if (playlist is null)
  179. {
  180. return NotFound("Playlist not found");
  181. }
  182. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  183. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  184. if (!isPermitted)
  185. {
  186. return Unauthorized("Unauthorized access");
  187. }
  188. await _playlistManager.AddToShares(playlistId, callingUserId, new PlaylistUserPermissions(userId.ToString(), canEdit)).ConfigureAwait(false);
  189. return NoContent();
  190. }
  191. /// <summary>
  192. /// Remove a user from a playlist's shares.
  193. /// </summary>
  194. /// <param name="playlistId">The playlist id.</param>
  195. /// <param name="userId">The user id.</param>
  196. /// <response code="204">User permissions removed from playlist.</response>
  197. /// <response code="401">Unauthorized access.</response>
  198. /// <response code="404">No playlist or user permissions found.</response>
  199. /// <returns>
  200. /// A <see cref="Task" /> that represents the asynchronous operation to delete a user from a playlist's shares.
  201. /// The task result contains an <see cref="OkResult"/> indicating success.
  202. /// </returns>
  203. [HttpDelete("{playlistId}/User/{userId}")]
  204. [ProducesResponseType(StatusCodes.Status204NoContent)]
  205. [ProducesResponseType(StatusCodes.Status401Unauthorized)]
  206. [ProducesResponseType(StatusCodes.Status404NotFound)]
  207. public async Task<ActionResult> RemoveUserFromPlaylist(
  208. [FromRoute, Required] Guid playlistId,
  209. [FromRoute, Required] Guid userId)
  210. {
  211. var callingUserId = User.GetUserId();
  212. var playlist = _playlistManager.GetPlaylist(callingUserId, playlistId);
  213. if (playlist is null)
  214. {
  215. return NotFound("Playlist not found");
  216. }
  217. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  218. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  219. if (!isPermitted)
  220. {
  221. return Unauthorized("Unauthorized access");
  222. }
  223. var share = playlist.Shares.FirstOrDefault(s => s.UserId.Equals(userId));
  224. if (share is null)
  225. {
  226. return NotFound("User permissions not found");
  227. }
  228. await _playlistManager.RemoveFromShares(playlistId, callingUserId, share).ConfigureAwait(false);
  229. return NoContent();
  230. }
  231. /// <summary>
  232. /// Adds items to a playlist.
  233. /// </summary>
  234. /// <param name="playlistId">The playlist id.</param>
  235. /// <param name="ids">Item id, comma delimited.</param>
  236. /// <param name="userId">The userId.</param>
  237. /// <response code="204">Items added to playlist.</response>
  238. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  239. [HttpPost("{playlistId}/Items")]
  240. [ProducesResponseType(StatusCodes.Status204NoContent)]
  241. public async Task<ActionResult> AddToPlaylist(
  242. [FromRoute, Required] Guid playlistId,
  243. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
  244. [FromQuery] Guid? userId)
  245. {
  246. userId = RequestHelpers.GetUserId(User, userId);
  247. await _playlistManager.AddToPlaylistAsync(playlistId, ids, userId.Value).ConfigureAwait(false);
  248. return NoContent();
  249. }
  250. /// <summary>
  251. /// Moves a playlist item.
  252. /// </summary>
  253. /// <param name="playlistId">The playlist id.</param>
  254. /// <param name="itemId">The item id.</param>
  255. /// <param name="newIndex">The new index.</param>
  256. /// <response code="204">Item moved to new index.</response>
  257. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  258. [HttpPost("{playlistId}/Items/{itemId}/Move/{newIndex}")]
  259. [ProducesResponseType(StatusCodes.Status204NoContent)]
  260. public async Task<ActionResult> MoveItem(
  261. [FromRoute, Required] string playlistId,
  262. [FromRoute, Required] string itemId,
  263. [FromRoute, Required] int newIndex)
  264. {
  265. await _playlistManager.MoveItemAsync(playlistId, itemId, newIndex).ConfigureAwait(false);
  266. return NoContent();
  267. }
  268. /// <summary>
  269. /// Removes items from a playlist.
  270. /// </summary>
  271. /// <param name="playlistId">The playlist id.</param>
  272. /// <param name="entryIds">The item ids, comma delimited.</param>
  273. /// <response code="204">Items removed.</response>
  274. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  275. [HttpDelete("{playlistId}/Items")]
  276. [ProducesResponseType(StatusCodes.Status204NoContent)]
  277. public async Task<ActionResult> RemoveFromPlaylist(
  278. [FromRoute, Required] string playlistId,
  279. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] entryIds)
  280. {
  281. await _playlistManager.RemoveFromPlaylistAsync(playlistId, entryIds).ConfigureAwait(false);
  282. return NoContent();
  283. }
  284. /// <summary>
  285. /// Gets the original items of a playlist.
  286. /// </summary>
  287. /// <param name="playlistId">The playlist id.</param>
  288. /// <param name="userId">User id.</param>
  289. /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
  290. /// <param name="limit">Optional. The maximum number of records to return.</param>
  291. /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
  292. /// <param name="enableImages">Optional. Include image information in output.</param>
  293. /// <param name="enableUserData">Optional. Include user data.</param>
  294. /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
  295. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  296. /// <response code="200">Original playlist returned.</response>
  297. /// <response code="404">Playlist not found.</response>
  298. /// <returns>The original playlist items.</returns>
  299. [HttpGet("{playlistId}/Items")]
  300. [ProducesResponseType(StatusCodes.Status200OK)]
  301. [ProducesResponseType(StatusCodes.Status404NotFound)]
  302. public ActionResult<QueryResult<BaseItemDto>> GetPlaylistItems(
  303. [FromRoute, Required] Guid playlistId,
  304. [FromQuery] Guid? userId,
  305. [FromQuery] int? startIndex,
  306. [FromQuery] int? limit,
  307. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  308. [FromQuery] bool? enableImages,
  309. [FromQuery] bool? enableUserData,
  310. [FromQuery] int? imageTypeLimit,
  311. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
  312. {
  313. userId = RequestHelpers.GetUserId(User, userId);
  314. var playlist = (Playlist)_libraryManager.GetItemById(playlistId);
  315. if (playlist is null)
  316. {
  317. return NotFound();
  318. }
  319. var user = userId.IsNullOrEmpty()
  320. ? null
  321. : _userManager.GetUserById(userId.Value);
  322. var items = playlist.GetManageableItems().ToArray();
  323. var count = items.Length;
  324. if (startIndex.HasValue)
  325. {
  326. items = items.Skip(startIndex.Value).ToArray();
  327. }
  328. if (limit.HasValue)
  329. {
  330. items = items.Take(limit.Value).ToArray();
  331. }
  332. var dtoOptions = new DtoOptions { Fields = fields }
  333. .AddClientFields(User)
  334. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  335. var dtos = _dtoService.GetBaseItemDtos(items.Select(i => i.Item2).ToList(), dtoOptions, user);
  336. for (int index = 0; index < dtos.Count; index++)
  337. {
  338. dtos[index].PlaylistItemId = items[index].Item1.Id;
  339. }
  340. var result = new QueryResult<BaseItemDto>(
  341. startIndex,
  342. count,
  343. dtos);
  344. return result;
  345. }
  346. }