PlaylistsController.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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?.IsPublic
  93. }).ConfigureAwait(false);
  94. return result;
  95. }
  96. /// <summary>
  97. /// Updates a playlist.
  98. /// </summary>
  99. /// <param name="playlistId">The playlist id.</param>
  100. /// <param name="updatePlaylistRequest">The <see cref="UpdatePlaylistDto"/> id.</param>
  101. /// <response code="204">Playlist updated.</response>
  102. /// <response code="403">Access forbidden.</response>
  103. /// <response code="404">Playlist not found.</response>
  104. /// <returns>
  105. /// A <see cref="Task" /> that represents the asynchronous operation to update a playlist.
  106. /// The task result contains an <see cref="OkResult"/> indicating success.
  107. /// </returns>
  108. [HttpPost("{playlistId}")]
  109. [ProducesResponseType(StatusCodes.Status204NoContent)]
  110. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  111. [ProducesResponseType(StatusCodes.Status404NotFound)]
  112. public async Task<ActionResult> UpdatePlaylist(
  113. [FromRoute, Required] Guid playlistId,
  114. [FromBody, Required] UpdatePlaylistDto updatePlaylistRequest)
  115. {
  116. var callingUserId = User.GetUserId();
  117. var playlist = _playlistManager.GetPlaylistForUser(playlistId, callingUserId);
  118. if (playlist is null)
  119. {
  120. return NotFound("Playlist not found");
  121. }
  122. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  123. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  124. if (!isPermitted)
  125. {
  126. return Forbid();
  127. }
  128. await _playlistManager.UpdatePlaylist(new PlaylistUpdateRequest
  129. {
  130. UserId = callingUserId,
  131. Id = playlistId,
  132. Name = updatePlaylistRequest.Name,
  133. Ids = updatePlaylistRequest.Ids,
  134. Users = updatePlaylistRequest.Users,
  135. Public = updatePlaylistRequest.IsPublic
  136. }).ConfigureAwait(false);
  137. return NoContent();
  138. }
  139. /// <summary>
  140. /// Get a playlist.
  141. /// </summary>
  142. /// <param name="playlistId">The playlist id.</param>
  143. /// <response code="200">The playlist.</response>
  144. /// <response code="404">Playlist not found.</response>
  145. /// <returns>
  146. /// A <see cref="Playlist"/> objects.
  147. /// </returns>
  148. [HttpGet("{playlistId}")]
  149. [ProducesResponseType(StatusCodes.Status200OK)]
  150. [ProducesResponseType(StatusCodes.Status404NotFound)]
  151. public ActionResult<PlaylistDto> GetPlaylist(
  152. [FromRoute, Required] Guid playlistId)
  153. {
  154. var userId = User.GetUserId();
  155. var playlist = _playlistManager.GetPlaylistForUser(playlistId, userId);
  156. if (playlist is null)
  157. {
  158. return NotFound("Playlist not found");
  159. }
  160. return new PlaylistDto()
  161. {
  162. Shares = playlist.Shares,
  163. OpenAccess = playlist.OpenAccess,
  164. ItemIds = playlist.GetManageableItems().Select(t => t.Item2.Id).ToList()
  165. };
  166. }
  167. /// <summary>
  168. /// Get a playlist's users.
  169. /// </summary>
  170. /// <param name="playlistId">The playlist id.</param>
  171. /// <response code="200">Found shares.</response>
  172. /// <response code="403">Access forbidden.</response>
  173. /// <response code="404">Playlist not found.</response>
  174. /// <returns>
  175. /// A list of <see cref="PlaylistUserPermissions"/> objects.
  176. /// </returns>
  177. [HttpGet("{playlistId}/Users")]
  178. [ProducesResponseType(StatusCodes.Status200OK)]
  179. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  180. [ProducesResponseType(StatusCodes.Status404NotFound)]
  181. public ActionResult<IReadOnlyList<PlaylistUserPermissions>> GetPlaylistUsers(
  182. [FromRoute, Required] Guid playlistId)
  183. {
  184. var userId = User.GetUserId();
  185. var playlist = _playlistManager.GetPlaylistForUser(playlistId, userId);
  186. if (playlist is null)
  187. {
  188. return NotFound("Playlist not found");
  189. }
  190. var isPermitted = playlist.OwnerUserId.Equals(userId);
  191. return isPermitted ? playlist.Shares.ToList() : Forbid();
  192. }
  193. /// <summary>
  194. /// Get a playlist user.
  195. /// </summary>
  196. /// <param name="playlistId">The playlist id.</param>
  197. /// <param name="userId">The user id.</param>
  198. /// <response code="200">User permission found.</response>
  199. /// <response code="403">Access forbidden.</response>
  200. /// <response code="404">Playlist not found.</response>
  201. /// <returns>
  202. /// <see cref="PlaylistUserPermissions"/>.
  203. /// </returns>
  204. [HttpGet("{playlistId}/Users/{userId}")]
  205. [ProducesResponseType(StatusCodes.Status200OK)]
  206. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  207. [ProducesResponseType(StatusCodes.Status404NotFound)]
  208. public ActionResult<PlaylistUserPermissions?> GetPlaylistUser(
  209. [FromRoute, Required] Guid playlistId,
  210. [FromRoute, Required] Guid userId)
  211. {
  212. var callingUserId = User.GetUserId();
  213. var playlist = _playlistManager.GetPlaylistForUser(playlistId, callingUserId);
  214. if (playlist is null)
  215. {
  216. return NotFound("Playlist not found");
  217. }
  218. if (playlist.OwnerUserId.Equals(callingUserId))
  219. {
  220. return new PlaylistUserPermissions(callingUserId, true);
  221. }
  222. var userPermission = playlist.Shares.FirstOrDefault(s => s.UserId.Equals(userId));
  223. var isPermitted = playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId))
  224. || userId.Equals(callingUserId);
  225. if (!isPermitted)
  226. {
  227. return Forbid();
  228. }
  229. if (userPermission is not null)
  230. {
  231. return userPermission;
  232. }
  233. return NotFound("User permissions not found");
  234. }
  235. /// <summary>
  236. /// Modify a user of a playlist's users.
  237. /// </summary>
  238. /// <param name="playlistId">The playlist id.</param>
  239. /// <param name="userId">The user id.</param>
  240. /// <param name="updatePlaylistUserRequest">The <see cref="UpdatePlaylistUserDto"/>.</param>
  241. /// <response code="204">User's permissions modified.</response>
  242. /// <response code="403">Access forbidden.</response>
  243. /// <response code="404">Playlist not found.</response>
  244. /// <returns>
  245. /// A <see cref="Task" /> that represents the asynchronous operation to modify an user's playlist permissions.
  246. /// The task result contains an <see cref="OkResult"/> indicating success.
  247. /// </returns>
  248. [HttpPost("{playlistId}/Users/{userId}")]
  249. [ProducesResponseType(StatusCodes.Status204NoContent)]
  250. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  251. [ProducesResponseType(StatusCodes.Status404NotFound)]
  252. public async Task<ActionResult> UpdatePlaylistUser(
  253. [FromRoute, Required] Guid playlistId,
  254. [FromRoute, Required] Guid userId,
  255. [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow), Required] UpdatePlaylistUserDto updatePlaylistUserRequest)
  256. {
  257. var callingUserId = User.GetUserId();
  258. var playlist = _playlistManager.GetPlaylistForUser(playlistId, callingUserId);
  259. if (playlist is null)
  260. {
  261. return NotFound("Playlist not found");
  262. }
  263. var isPermitted = playlist.OwnerUserId.Equals(callingUserId);
  264. if (!isPermitted)
  265. {
  266. return Forbid();
  267. }
  268. await _playlistManager.AddUserToShares(new PlaylistUserUpdateRequest
  269. {
  270. Id = playlistId,
  271. UserId = userId,
  272. CanEdit = updatePlaylistUserRequest.CanEdit
  273. }).ConfigureAwait(false);
  274. return NoContent();
  275. }
  276. /// <summary>
  277. /// Remove a user from a playlist's users.
  278. /// </summary>
  279. /// <param name="playlistId">The playlist id.</param>
  280. /// <param name="userId">The user id.</param>
  281. /// <response code="204">User permissions removed from playlist.</response>
  282. /// <response code="401">Unauthorized access.</response>
  283. /// <response code="404">No playlist or user permissions found.</response>
  284. /// <returns>
  285. /// A <see cref="Task" /> that represents the asynchronous operation to delete a user from a playlist's shares.
  286. /// The task result contains an <see cref="OkResult"/> indicating success.
  287. /// </returns>
  288. [HttpDelete("{playlistId}/Users/{userId}")]
  289. [ProducesResponseType(StatusCodes.Status204NoContent)]
  290. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  291. [ProducesResponseType(StatusCodes.Status404NotFound)]
  292. public async Task<ActionResult> RemoveUserFromPlaylist(
  293. [FromRoute, Required] Guid playlistId,
  294. [FromRoute, Required] Guid userId)
  295. {
  296. var callingUserId = User.GetUserId();
  297. var playlist = _playlistManager.GetPlaylistForUser(playlistId, callingUserId);
  298. if (playlist is null)
  299. {
  300. return NotFound("Playlist not found");
  301. }
  302. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  303. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  304. if (!isPermitted)
  305. {
  306. return Forbid();
  307. }
  308. var share = playlist.Shares.FirstOrDefault(s => s.UserId.Equals(userId));
  309. if (share is null)
  310. {
  311. return NotFound("User permissions not found");
  312. }
  313. await _playlistManager.RemoveUserFromShares(playlistId, callingUserId, share).ConfigureAwait(false);
  314. return NoContent();
  315. }
  316. /// <summary>
  317. /// Adds items to a playlist.
  318. /// </summary>
  319. /// <param name="playlistId">The playlist id.</param>
  320. /// <param name="ids">Item id, comma delimited.</param>
  321. /// <param name="userId">The userId.</param>
  322. /// <response code="204">Items added to playlist.</response>
  323. /// <response code="403">Access forbidden.</response>
  324. /// <response code="404">Playlist not found.</response>
  325. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  326. [HttpPost("{playlistId}/Items")]
  327. [ProducesResponseType(StatusCodes.Status204NoContent)]
  328. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  329. [ProducesResponseType(StatusCodes.Status404NotFound)]
  330. public async Task<ActionResult> AddItemToPlaylist(
  331. [FromRoute, Required] Guid playlistId,
  332. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
  333. [FromQuery] Guid? userId)
  334. {
  335. userId = RequestHelpers.GetUserId(User, userId);
  336. var playlist = _playlistManager.GetPlaylistForUser(playlistId, userId.Value);
  337. if (playlist is null)
  338. {
  339. return NotFound("Playlist not found");
  340. }
  341. var isPermitted = playlist.OwnerUserId.Equals(userId.Value)
  342. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(userId.Value));
  343. if (!isPermitted)
  344. {
  345. return Forbid();
  346. }
  347. await _playlistManager.AddItemToPlaylistAsync(playlistId, ids, userId.Value).ConfigureAwait(false);
  348. return NoContent();
  349. }
  350. /// <summary>
  351. /// Moves a playlist item.
  352. /// </summary>
  353. /// <param name="playlistId">The playlist id.</param>
  354. /// <param name="itemId">The item id.</param>
  355. /// <param name="newIndex">The new index.</param>
  356. /// <response code="204">Item moved to new index.</response>
  357. /// <response code="403">Access forbidden.</response>
  358. /// <response code="404">Playlist not found.</response>
  359. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  360. [HttpPost("{playlistId}/Items/{itemId}/Move/{newIndex}")]
  361. [ProducesResponseType(StatusCodes.Status204NoContent)]
  362. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  363. [ProducesResponseType(StatusCodes.Status404NotFound)]
  364. public async Task<ActionResult> MoveItem(
  365. [FromRoute, Required] string playlistId,
  366. [FromRoute, Required] string itemId,
  367. [FromRoute, Required] int newIndex)
  368. {
  369. var callingUserId = User.GetUserId();
  370. var playlist = _playlistManager.GetPlaylistForUser(Guid.Parse(playlistId), callingUserId);
  371. if (playlist is null)
  372. {
  373. return NotFound("Playlist not found");
  374. }
  375. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  376. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  377. if (!isPermitted)
  378. {
  379. return Forbid();
  380. }
  381. await _playlistManager.MoveItemAsync(playlistId, itemId, newIndex).ConfigureAwait(false);
  382. return NoContent();
  383. }
  384. /// <summary>
  385. /// Removes items from a playlist.
  386. /// </summary>
  387. /// <param name="playlistId">The playlist id.</param>
  388. /// <param name="entryIds">The item ids, comma delimited.</param>
  389. /// <response code="204">Items removed.</response>
  390. /// <response code="403">Access forbidden.</response>
  391. /// <response code="404">Playlist not found.</response>
  392. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  393. [HttpDelete("{playlistId}/Items")]
  394. [ProducesResponseType(StatusCodes.Status204NoContent)]
  395. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  396. [ProducesResponseType(StatusCodes.Status404NotFound)]
  397. public async Task<ActionResult> RemoveItemFromPlaylist(
  398. [FromRoute, Required] string playlistId,
  399. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] entryIds)
  400. {
  401. var callingUserId = User.GetUserId();
  402. var playlist = _playlistManager.GetPlaylistForUser(Guid.Parse(playlistId), callingUserId);
  403. if (playlist is null)
  404. {
  405. return NotFound("Playlist not found");
  406. }
  407. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  408. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  409. if (!isPermitted)
  410. {
  411. return Forbid();
  412. }
  413. await _playlistManager.RemoveItemFromPlaylistAsync(playlistId, entryIds).ConfigureAwait(false);
  414. return NoContent();
  415. }
  416. /// <summary>
  417. /// Gets the original items of a playlist.
  418. /// </summary>
  419. /// <param name="playlistId">The playlist id.</param>
  420. /// <param name="userId">User id.</param>
  421. /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
  422. /// <param name="limit">Optional. The maximum number of records to return.</param>
  423. /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
  424. /// <param name="enableImages">Optional. Include image information in output.</param>
  425. /// <param name="enableUserData">Optional. Include user data.</param>
  426. /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
  427. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  428. /// <response code="200">Original playlist returned.</response>
  429. /// <response code="404">Access forbidden.</response>
  430. /// <response code="404">Playlist not found.</response>
  431. /// <returns>The original playlist items.</returns>
  432. [HttpGet("{playlistId}/Items")]
  433. [ProducesResponseType(StatusCodes.Status200OK)]
  434. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  435. [ProducesResponseType(StatusCodes.Status404NotFound)]
  436. public ActionResult<QueryResult<BaseItemDto>> GetPlaylistItems(
  437. [FromRoute, Required] Guid playlistId,
  438. [FromQuery] Guid? userId,
  439. [FromQuery] int? startIndex,
  440. [FromQuery] int? limit,
  441. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  442. [FromQuery] bool? enableImages,
  443. [FromQuery] bool? enableUserData,
  444. [FromQuery] int? imageTypeLimit,
  445. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
  446. {
  447. var callingUserId = userId ?? User.GetUserId();
  448. var playlist = _playlistManager.GetPlaylistForUser(playlistId, callingUserId);
  449. if (playlist is null)
  450. {
  451. return NotFound("Playlist not found");
  452. }
  453. var isPermitted = playlist.OpenAccess
  454. || playlist.OwnerUserId.Equals(callingUserId)
  455. || playlist.Shares.Any(s => s.UserId.Equals(callingUserId));
  456. if (!isPermitted)
  457. {
  458. return Forbid();
  459. }
  460. var items = playlist.GetManageableItems().ToArray();
  461. var count = items.Length;
  462. if (startIndex.HasValue)
  463. {
  464. items = items.Skip(startIndex.Value).ToArray();
  465. }
  466. if (limit.HasValue)
  467. {
  468. items = items.Take(limit.Value).ToArray();
  469. }
  470. var dtoOptions = new DtoOptions { Fields = fields }
  471. .AddClientFields(User)
  472. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  473. var user = _userManager.GetUserById(callingUserId);
  474. var dtos = _dtoService.GetBaseItemDtos(items.Select(i => i.Item2).ToList(), dtoOptions, user);
  475. for (int index = 0; index < dtos.Count; index++)
  476. {
  477. dtos[index].PlaylistItemId = items[index].Item1.Id;
  478. }
  479. var result = new QueryResult<BaseItemDto>(
  480. startIndex,
  481. count,
  482. dtos);
  483. return result;
  484. }
  485. }