PlaylistsController.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using Jellyfin.Api.Attributes;
  8. using Jellyfin.Api.Extensions;
  9. using Jellyfin.Api.Helpers;
  10. using Jellyfin.Api.ModelBinders;
  11. using Jellyfin.Api.Models.PlaylistDtos;
  12. using Jellyfin.Data.Enums;
  13. using Jellyfin.Extensions;
  14. using MediaBrowser.Controller.Dto;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Controller.Playlists;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.Playlists;
  20. using MediaBrowser.Model.Querying;
  21. using Microsoft.AspNetCore.Authorization;
  22. using Microsoft.AspNetCore.Http;
  23. using Microsoft.AspNetCore.Mvc;
  24. using Microsoft.AspNetCore.Mvc.ModelBinding;
  25. namespace Jellyfin.Api.Controllers;
  26. /// <summary>
  27. /// Playlists controller.
  28. /// </summary>
  29. [Authorize]
  30. public class PlaylistsController : BaseJellyfinApiController
  31. {
  32. private readonly IPlaylistManager _playlistManager;
  33. private readonly IDtoService _dtoService;
  34. private readonly IUserManager _userManager;
  35. private readonly ILibraryManager _libraryManager;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="PlaylistsController"/> class.
  38. /// </summary>
  39. /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
  40. /// <param name="playlistManager">Instance of the <see cref="IPlaylistManager"/> interface.</param>
  41. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  42. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  43. public PlaylistsController(
  44. IDtoService dtoService,
  45. IPlaylistManager playlistManager,
  46. IUserManager userManager,
  47. ILibraryManager libraryManager)
  48. {
  49. _dtoService = dtoService;
  50. _playlistManager = playlistManager;
  51. _userManager = userManager;
  52. _libraryManager = libraryManager;
  53. }
  54. /// <summary>
  55. /// Creates a new playlist.
  56. /// </summary>
  57. /// <remarks>
  58. /// For backwards compatibility parameters can be sent via Query or Body, with Query having higher precedence.
  59. /// Query parameters are obsolete.
  60. /// </remarks>
  61. /// <param name="name">The playlist name.</param>
  62. /// <param name="ids">The item ids.</param>
  63. /// <param name="userId">The user id.</param>
  64. /// <param name="mediaType">The media type.</param>
  65. /// <param name="createPlaylistRequest">The create playlist payload.</param>
  66. /// <response code="200">Playlist created.</response>
  67. /// <returns>
  68. /// A <see cref="Task" /> that represents the asynchronous operation to create a playlist.
  69. /// The task result contains an <see cref="OkResult"/> indicating success.
  70. /// </returns>
  71. [HttpPost]
  72. [ProducesResponseType(StatusCodes.Status200OK)]
  73. public async Task<ActionResult<PlaylistCreationResult>> CreatePlaylist(
  74. [FromQuery, ParameterObsolete] string? name,
  75. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder)), ParameterObsolete] IReadOnlyList<Guid> ids,
  76. [FromQuery, ParameterObsolete] Guid? userId,
  77. [FromQuery, ParameterObsolete] MediaType? mediaType,
  78. [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] CreatePlaylistDto? createPlaylistRequest)
  79. {
  80. if (ids.Count == 0)
  81. {
  82. ids = createPlaylistRequest?.Ids ?? Array.Empty<Guid>();
  83. }
  84. userId ??= createPlaylistRequest?.UserId ?? default;
  85. userId = RequestHelpers.GetUserId(User, userId);
  86. var result = await _playlistManager.CreatePlaylist(new PlaylistCreationRequest
  87. {
  88. Name = name ?? createPlaylistRequest?.Name,
  89. ItemIdList = ids,
  90. UserId = userId.Value,
  91. MediaType = mediaType ?? createPlaylistRequest?.MediaType,
  92. Users = createPlaylistRequest?.Users.ToArray() ?? [],
  93. Public = createPlaylistRequest?.IsPublic
  94. }).ConfigureAwait(false);
  95. return result;
  96. }
  97. /// <summary>
  98. /// Updates a playlist.
  99. /// </summary>
  100. /// <param name="playlistId">The playlist id.</param>
  101. /// <param name="updatePlaylistRequest">The <see cref="UpdatePlaylistDto"/> id.</param>
  102. /// <response code="204">Playlist updated.</response>
  103. /// <response code="403">Access forbidden.</response>
  104. /// <response code="404">Playlist not found.</response>
  105. /// <returns>
  106. /// A <see cref="Task" /> that represents the asynchronous operation to update a playlist.
  107. /// The task result contains an <see cref="OkResult"/> indicating success.
  108. /// </returns>
  109. [HttpPost("{playlistId}")]
  110. [ProducesResponseType(StatusCodes.Status204NoContent)]
  111. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  112. [ProducesResponseType(StatusCodes.Status404NotFound)]
  113. public async Task<ActionResult> UpdatePlaylist(
  114. [FromRoute, Required] Guid playlistId,
  115. [FromBody, Required] UpdatePlaylistDto updatePlaylistRequest)
  116. {
  117. var callingUserId = User.GetUserId();
  118. var playlist = _playlistManager.GetPlaylistForUser(playlistId, callingUserId);
  119. if (playlist is null)
  120. {
  121. return NotFound("Playlist not found");
  122. }
  123. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  124. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  125. if (!isPermitted)
  126. {
  127. return Forbid();
  128. }
  129. await _playlistManager.UpdatePlaylist(new PlaylistUpdateRequest
  130. {
  131. UserId = callingUserId,
  132. Id = playlistId,
  133. Name = updatePlaylistRequest.Name,
  134. Ids = updatePlaylistRequest.Ids,
  135. Users = updatePlaylistRequest.Users,
  136. Public = updatePlaylistRequest.IsPublic
  137. }).ConfigureAwait(false);
  138. return NoContent();
  139. }
  140. /// <summary>
  141. /// Get a playlist.
  142. /// </summary>
  143. /// <param name="playlistId">The playlist id.</param>
  144. /// <response code="200">The playlist.</response>
  145. /// <response code="404">Playlist not found.</response>
  146. /// <returns>
  147. /// A <see cref="Playlist"/> objects.
  148. /// </returns>
  149. [HttpGet("{playlistId}")]
  150. [ProducesResponseType(StatusCodes.Status200OK)]
  151. [ProducesResponseType(StatusCodes.Status404NotFound)]
  152. public ActionResult<PlaylistDto> GetPlaylist(
  153. [FromRoute, Required] Guid playlistId)
  154. {
  155. var userId = User.GetUserId();
  156. var playlist = _playlistManager.GetPlaylistForUser(playlistId, userId);
  157. if (playlist is null)
  158. {
  159. return NotFound("Playlist not found");
  160. }
  161. return new PlaylistDto()
  162. {
  163. Shares = playlist.Shares,
  164. OpenAccess = playlist.OpenAccess,
  165. ItemIds = playlist.GetManageableItems().Select(t => t.Item2.Id).ToList()
  166. };
  167. }
  168. /// <summary>
  169. /// Get a playlist's users.
  170. /// </summary>
  171. /// <param name="playlistId">The playlist id.</param>
  172. /// <response code="200">Found shares.</response>
  173. /// <response code="403">Access forbidden.</response>
  174. /// <response code="404">Playlist not found.</response>
  175. /// <returns>
  176. /// A list of <see cref="PlaylistUserPermissions"/> objects.
  177. /// </returns>
  178. [HttpGet("{playlistId}/Users")]
  179. [ProducesResponseType(StatusCodes.Status200OK)]
  180. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  181. [ProducesResponseType(StatusCodes.Status404NotFound)]
  182. public ActionResult<IReadOnlyList<PlaylistUserPermissions>> GetPlaylistUsers(
  183. [FromRoute, Required] Guid playlistId)
  184. {
  185. var userId = User.GetUserId();
  186. var playlist = _playlistManager.GetPlaylistForUser(playlistId, userId);
  187. if (playlist is null)
  188. {
  189. return NotFound("Playlist not found");
  190. }
  191. var isPermitted = playlist.OwnerUserId.Equals(userId);
  192. return isPermitted ? playlist.Shares.ToList() : Forbid();
  193. }
  194. /// <summary>
  195. /// Get a playlist user.
  196. /// </summary>
  197. /// <param name="playlistId">The playlist id.</param>
  198. /// <param name="userId">The user id.</param>
  199. /// <response code="200">User permission found.</response>
  200. /// <response code="403">Access forbidden.</response>
  201. /// <response code="404">Playlist not found.</response>
  202. /// <returns>
  203. /// <see cref="PlaylistUserPermissions"/>.
  204. /// </returns>
  205. [HttpGet("{playlistId}/Users/{userId}")]
  206. [ProducesResponseType(StatusCodes.Status200OK)]
  207. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  208. [ProducesResponseType(StatusCodes.Status404NotFound)]
  209. public ActionResult<PlaylistUserPermissions?> GetPlaylistUser(
  210. [FromRoute, Required] Guid playlistId,
  211. [FromRoute, Required] Guid userId)
  212. {
  213. var callingUserId = User.GetUserId();
  214. var playlist = _playlistManager.GetPlaylistForUser(playlistId, callingUserId);
  215. if (playlist is null)
  216. {
  217. return NotFound("Playlist not found");
  218. }
  219. if (playlist.OwnerUserId.Equals(callingUserId))
  220. {
  221. return new PlaylistUserPermissions(callingUserId, true);
  222. }
  223. var userPermission = playlist.Shares.FirstOrDefault(s => s.UserId.Equals(userId));
  224. var isPermitted = playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId))
  225. || userId.Equals(callingUserId);
  226. if (!isPermitted)
  227. {
  228. return Forbid();
  229. }
  230. if (userPermission is not null)
  231. {
  232. return userPermission;
  233. }
  234. return NotFound("User permissions not found");
  235. }
  236. /// <summary>
  237. /// Modify a user of a playlist's users.
  238. /// </summary>
  239. /// <param name="playlistId">The playlist id.</param>
  240. /// <param name="userId">The user id.</param>
  241. /// <param name="updatePlaylistUserRequest">The <see cref="UpdatePlaylistUserDto"/>.</param>
  242. /// <response code="204">User's permissions modified.</response>
  243. /// <response code="403">Access forbidden.</response>
  244. /// <response code="404">Playlist not found.</response>
  245. /// <returns>
  246. /// A <see cref="Task" /> that represents the asynchronous operation to modify an user's playlist permissions.
  247. /// The task result contains an <see cref="OkResult"/> indicating success.
  248. /// </returns>
  249. [HttpPost("{playlistId}/Users/{userId}")]
  250. [ProducesResponseType(StatusCodes.Status204NoContent)]
  251. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  252. [ProducesResponseType(StatusCodes.Status404NotFound)]
  253. public async Task<ActionResult> UpdatePlaylistUser(
  254. [FromRoute, Required] Guid playlistId,
  255. [FromRoute, Required] Guid userId,
  256. [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow), Required] UpdatePlaylistUserDto updatePlaylistUserRequest)
  257. {
  258. var callingUserId = User.GetUserId();
  259. var playlist = _playlistManager.GetPlaylistForUser(playlistId, callingUserId);
  260. if (playlist is null)
  261. {
  262. return NotFound("Playlist not found");
  263. }
  264. var isPermitted = playlist.OwnerUserId.Equals(callingUserId);
  265. if (!isPermitted)
  266. {
  267. return Forbid();
  268. }
  269. await _playlistManager.AddUserToShares(new PlaylistUserUpdateRequest
  270. {
  271. Id = playlistId,
  272. UserId = userId,
  273. CanEdit = updatePlaylistUserRequest.CanEdit
  274. }).ConfigureAwait(false);
  275. return NoContent();
  276. }
  277. /// <summary>
  278. /// Remove a user from a playlist's users.
  279. /// </summary>
  280. /// <param name="playlistId">The playlist id.</param>
  281. /// <param name="userId">The user id.</param>
  282. /// <response code="204">User permissions removed from playlist.</response>
  283. /// <response code="401">Unauthorized access.</response>
  284. /// <response code="404">No playlist or user permissions found.</response>
  285. /// <returns>
  286. /// A <see cref="Task" /> that represents the asynchronous operation to delete a user from a playlist's shares.
  287. /// The task result contains an <see cref="OkResult"/> indicating success.
  288. /// </returns>
  289. [HttpDelete("{playlistId}/Users/{userId}")]
  290. [ProducesResponseType(StatusCodes.Status204NoContent)]
  291. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  292. [ProducesResponseType(StatusCodes.Status404NotFound)]
  293. public async Task<ActionResult> RemoveUserFromPlaylist(
  294. [FromRoute, Required] Guid playlistId,
  295. [FromRoute, Required] Guid userId)
  296. {
  297. var callingUserId = User.GetUserId();
  298. var playlist = _playlistManager.GetPlaylistForUser(playlistId, callingUserId);
  299. if (playlist is null)
  300. {
  301. return NotFound("Playlist not found");
  302. }
  303. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  304. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  305. if (!isPermitted)
  306. {
  307. return Forbid();
  308. }
  309. var share = playlist.Shares.FirstOrDefault(s => s.UserId.Equals(userId));
  310. if (share is null)
  311. {
  312. return NotFound("User permissions not found");
  313. }
  314. await _playlistManager.RemoveUserFromShares(playlistId, callingUserId, share).ConfigureAwait(false);
  315. return NoContent();
  316. }
  317. /// <summary>
  318. /// Adds items to a playlist.
  319. /// </summary>
  320. /// <param name="playlistId">The playlist id.</param>
  321. /// <param name="ids">Item id, comma delimited.</param>
  322. /// <param name="userId">The userId.</param>
  323. /// <response code="204">Items added to playlist.</response>
  324. /// <response code="403">Access forbidden.</response>
  325. /// <response code="404">Playlist not found.</response>
  326. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  327. [HttpPost("{playlistId}/Items")]
  328. [ProducesResponseType(StatusCodes.Status204NoContent)]
  329. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  330. [ProducesResponseType(StatusCodes.Status404NotFound)]
  331. public async Task<ActionResult> AddItemToPlaylist(
  332. [FromRoute, Required] Guid playlistId,
  333. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
  334. [FromQuery] Guid? userId)
  335. {
  336. userId = RequestHelpers.GetUserId(User, userId);
  337. var playlist = _playlistManager.GetPlaylistForUser(playlistId, userId.Value);
  338. if (playlist is null)
  339. {
  340. return NotFound("Playlist not found");
  341. }
  342. var isPermitted = playlist.OwnerUserId.Equals(userId.Value)
  343. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(userId.Value));
  344. if (!isPermitted)
  345. {
  346. return Forbid();
  347. }
  348. await _playlistManager.AddItemToPlaylistAsync(playlistId, ids, userId.Value).ConfigureAwait(false);
  349. return NoContent();
  350. }
  351. /// <summary>
  352. /// Moves a playlist item.
  353. /// </summary>
  354. /// <param name="playlistId">The playlist id.</param>
  355. /// <param name="itemId">The item id.</param>
  356. /// <param name="newIndex">The new index.</param>
  357. /// <response code="204">Item moved to new index.</response>
  358. /// <response code="403">Access forbidden.</response>
  359. /// <response code="404">Playlist not found.</response>
  360. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  361. [HttpPost("{playlistId}/Items/{itemId}/Move/{newIndex}")]
  362. [ProducesResponseType(StatusCodes.Status204NoContent)]
  363. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  364. [ProducesResponseType(StatusCodes.Status404NotFound)]
  365. public async Task<ActionResult> MoveItem(
  366. [FromRoute, Required] string playlistId,
  367. [FromRoute, Required] string itemId,
  368. [FromRoute, Required] int newIndex)
  369. {
  370. var callingUserId = User.GetUserId();
  371. var playlist = _playlistManager.GetPlaylistForUser(Guid.Parse(playlistId), callingUserId);
  372. if (playlist is null)
  373. {
  374. return NotFound("Playlist not found");
  375. }
  376. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  377. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  378. if (!isPermitted)
  379. {
  380. return Forbid();
  381. }
  382. await _playlistManager.MoveItemAsync(playlistId, itemId, newIndex, callingUserId).ConfigureAwait(false);
  383. return NoContent();
  384. }
  385. /// <summary>
  386. /// Removes items from a playlist.
  387. /// </summary>
  388. /// <param name="playlistId">The playlist id.</param>
  389. /// <param name="entryIds">The item ids, comma delimited.</param>
  390. /// <response code="204">Items removed.</response>
  391. /// <response code="403">Access forbidden.</response>
  392. /// <response code="404">Playlist not found.</response>
  393. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  394. [HttpDelete("{playlistId}/Items")]
  395. [ProducesResponseType(StatusCodes.Status204NoContent)]
  396. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  397. [ProducesResponseType(StatusCodes.Status404NotFound)]
  398. public async Task<ActionResult> RemoveItemFromPlaylist(
  399. [FromRoute, Required] string playlistId,
  400. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] entryIds)
  401. {
  402. var callingUserId = User.GetUserId();
  403. var playlist = _playlistManager.GetPlaylistForUser(Guid.Parse(playlistId), callingUserId);
  404. if (playlist is null)
  405. {
  406. return NotFound("Playlist not found");
  407. }
  408. var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
  409. || playlist.Shares.Any(s => s.CanEdit && s.UserId.Equals(callingUserId));
  410. if (!isPermitted)
  411. {
  412. return Forbid();
  413. }
  414. await _playlistManager.RemoveItemFromPlaylistAsync(playlistId, entryIds).ConfigureAwait(false);
  415. return NoContent();
  416. }
  417. /// <summary>
  418. /// Gets the original items of a playlist.
  419. /// </summary>
  420. /// <param name="playlistId">The playlist id.</param>
  421. /// <param name="userId">User id.</param>
  422. /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
  423. /// <param name="limit">Optional. The maximum number of records to return.</param>
  424. /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
  425. /// <param name="enableImages">Optional. Include image information in output.</param>
  426. /// <param name="enableUserData">Optional. Include user data.</param>
  427. /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
  428. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  429. /// <response code="200">Original playlist returned.</response>
  430. /// <response code="404">Access forbidden.</response>
  431. /// <response code="404">Playlist not found.</response>
  432. /// <returns>The original playlist items.</returns>
  433. [HttpGet("{playlistId}/Items")]
  434. [ProducesResponseType(StatusCodes.Status200OK)]
  435. [ProducesResponseType(StatusCodes.Status403Forbidden)]
  436. [ProducesResponseType(StatusCodes.Status404NotFound)]
  437. public ActionResult<QueryResult<BaseItemDto>> GetPlaylistItems(
  438. [FromRoute, Required] Guid playlistId,
  439. [FromQuery] Guid? userId,
  440. [FromQuery] int? startIndex,
  441. [FromQuery] int? limit,
  442. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  443. [FromQuery] bool? enableImages,
  444. [FromQuery] bool? enableUserData,
  445. [FromQuery] int? imageTypeLimit,
  446. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
  447. {
  448. var callingUserId = userId ?? User.GetUserId();
  449. var playlist = _playlistManager.GetPlaylistForUser(playlistId, callingUserId);
  450. if (playlist is null)
  451. {
  452. return NotFound("Playlist not found");
  453. }
  454. var isPermitted = playlist.OpenAccess
  455. || playlist.OwnerUserId.Equals(callingUserId)
  456. || playlist.Shares.Any(s => s.UserId.Equals(callingUserId));
  457. if (!isPermitted)
  458. {
  459. return Forbid();
  460. }
  461. var user = _userManager.GetUserById(callingUserId);
  462. var items = playlist.GetManageableItems().Where(i => i.Item2.IsVisible(user)).ToArray();
  463. var count = items.Length;
  464. if (startIndex.HasValue)
  465. {
  466. items = items.Skip(startIndex.Value).ToArray();
  467. }
  468. if (limit.HasValue)
  469. {
  470. items = items.Take(limit.Value).ToArray();
  471. }
  472. var dtoOptions = new DtoOptions { Fields = fields }
  473. .AddClientFields(User)
  474. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  475. var dtos = _dtoService.GetBaseItemDtos(items.Select(i => i.Item2).ToList(), dtoOptions, user);
  476. for (int index = 0; index < dtos.Count; index++)
  477. {
  478. dtos[index].PlaylistItemId = items[index].Item1.ItemId?.ToString("N", CultureInfo.InvariantCulture);
  479. }
  480. var result = new QueryResult<BaseItemDto>(
  481. startIndex,
  482. count,
  483. dtos);
  484. return result;
  485. }
  486. }