aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/Controllers/PlaylistsController.cs
blob: bf618e8fd79940801240f9b80ddadfe9c2d550c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Api.Attributes;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Api.Models.PlaylistDtos;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Playlists;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Jellyfin.Api.Controllers;

/// <summary>
/// Playlists controller.
/// </summary>
[Authorize]
public class PlaylistsController : BaseJellyfinApiController
{
    private readonly IPlaylistManager _playlistManager;
    private readonly IDtoService _dtoService;
    private readonly IUserManager _userManager;
    private readonly ILibraryManager _libraryManager;

    /// <summary>
    /// Initializes a new instance of the <see cref="PlaylistsController"/> class.
    /// </summary>
    /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
    /// <param name="playlistManager">Instance of the <see cref="IPlaylistManager"/> interface.</param>
    /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
    /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
    public PlaylistsController(
        IDtoService dtoService,
        IPlaylistManager playlistManager,
        IUserManager userManager,
        ILibraryManager libraryManager)
    {
        _dtoService = dtoService;
        _playlistManager = playlistManager;
        _userManager = userManager;
        _libraryManager = libraryManager;
    }

    /// <summary>
    /// Creates a new playlist.
    /// </summary>
    /// <remarks>
    /// For backwards compatibility parameters can be sent via Query or Body, with Query having higher precedence.
    /// Query parameters are obsolete.
    /// </remarks>
    /// <param name="name">The playlist name.</param>
    /// <param name="ids">The item ids.</param>
    /// <param name="userId">The user id.</param>
    /// <param name="mediaType">The media type.</param>
    /// <param name="createPlaylistRequest">The create playlist payload.</param>
    /// <response code="200">Playlist created.</response>
    /// <returns>
    /// A <see cref="Task" /> that represents the asynchronous operation to create a playlist.
    /// The task result contains an <see cref="OkResult"/> indicating success.
    /// </returns>
    [HttpPost]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult<PlaylistCreationResult>> CreatePlaylist(
        [FromQuery, ParameterObsolete] string? name,
        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder)), ParameterObsolete] IReadOnlyList<Guid> ids,
        [FromQuery, ParameterObsolete] Guid? userId,
        [FromQuery, ParameterObsolete] MediaType? mediaType,
        [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] CreatePlaylistDto? createPlaylistRequest)
    {
        if (ids.Count == 0)
        {
            ids = createPlaylistRequest?.Ids ?? Array.Empty<Guid>();
        }

        userId ??= createPlaylistRequest?.UserId ?? default;
        userId = RequestHelpers.GetUserId(User, userId);
        var result = await _playlistManager.CreatePlaylist(new PlaylistCreationRequest
        {
            Name = name ?? createPlaylistRequest?.Name,
            ItemIdList = ids,
            UserId = userId.Value,
            MediaType = mediaType ?? createPlaylistRequest?.MediaType,
            Shares = createPlaylistRequest?.Shares.ToArray(),
            OpenAccess = createPlaylistRequest?.OpenAccess
        }).ConfigureAwait(false);

        return result;
    }

    /// <summary>
    /// Get a playlist's shares.
    /// </summary>
    /// <param name="playlistId">The playlist id.</param>
    /// <returns>
    /// A list of <see cref="Share"/> objects.
    /// </returns>
    [HttpGet("{playlistId}/Shares")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public IReadOnlyList<Share> GetPlaylistShares(
        [FromRoute, Required] Guid playlistId)
    {
        var userId = RequestHelpers.GetUserId(User, default);

        var playlist = _playlistManager.GetPlaylist(userId, playlistId);
        var isPermitted = playlist.OwnerUserId.Equals(userId)
            || playlist.Shares.Any(s => s.CanEdit && (s.UserId?.Equals(userId) ?? false));

        return isPermitted ? playlist.Shares : new List<Share>();
    }

    /// <summary>
    /// Toggles OpenAccess of a playlist.
    /// </summary>
    /// <param name="playlistId">The playlist id.</param>
    /// <returns>
    /// A <see cref="Task" /> that represents the asynchronous operation to toggle OpenAccess of a playlist.
    /// The task result contains an <see cref="OkResult"/> indicating success.
    /// </returns>
    [HttpPost("{playlistId}/ToggleOpenAccess")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult> ToggleopenAccess(
        [FromRoute, Required] Guid playlistId)
    {
        var callingUserId = RequestHelpers.GetUserId(User, default);

        var playlist = _playlistManager.GetPlaylist(callingUserId, playlistId);
        var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
            || playlist.Shares.Any(s => s.CanEdit && (s.UserId?.Equals(callingUserId) ?? false));

        if (!isPermitted)
        {
            return Unauthorized("Unauthorized access");
        }

        await _playlistManager.ToggleOpenAccess(playlistId, callingUserId).ConfigureAwait(false);

        return NoContent();
    }

    /// <summary>
    /// Adds shares to a playlist's shares.
    /// </summary>
    /// <param name="playlistId">The playlist id.</param>
    /// <param name="shares">The shares.</param>
    /// <returns>
    /// A <see cref="Task" /> that represents the asynchronous operation to add shares to a playlist.
    /// The task result contains an <see cref="OkResult"/> indicating success.
    /// </returns>
    [HttpPost("{playlistId}/Shares")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult> AddUserToPlaylistShares(
        [FromRoute, Required] Guid playlistId,
        [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Disallow)] Share[] shares)
    {
        var callingUserId = RequestHelpers.GetUserId(User, default);

        var playlist = _playlistManager.GetPlaylist(callingUserId, playlistId);
        var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
            || playlist.Shares.Any(s => s.CanEdit && (s.UserId?.Equals(callingUserId) ?? false));

        if (!isPermitted)
        {
            return Unauthorized("Unauthorized access");
        }

        foreach (var share in shares)
        {
            await _playlistManager.AddToShares(playlistId, callingUserId, share).ConfigureAwait(false);
        }

        return NoContent();
    }

    /// <summary>
    /// Remove a user from a playlist's shares.
    /// </summary>
    /// <param name="playlistId">The playlist id.</param>
    /// <param name="userId">The user id.</param>
    /// <returns>
    /// A <see cref="Task" /> that represents the asynchronous operation to delete a user from a playlist's shares.
    /// The task result contains an <see cref="OkResult"/> indicating success.
    /// </returns>
    [HttpDelete("{playlistId}/Shares")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult> RemoveUserFromPlaylistShares(
        [FromRoute, Required] Guid playlistId,
        [FromBody] Guid userId)
    {
        var callingUserId = RequestHelpers.GetUserId(User, default);

        var playlist = _playlistManager.GetPlaylist(callingUserId, playlistId);
        var isPermitted = playlist.OwnerUserId.Equals(callingUserId)
            || playlist.Shares.Any(s => s.CanEdit && (s.UserId?.Equals(callingUserId) ?? false));

        if (!isPermitted)
        {
            return Unauthorized("Unauthorized access");
        }

        var share = playlist.Shares.FirstOrDefault(s => s.UserId?.Equals(userId) ?? false);

        if (share is null)
        {
            return NotFound();
        }

        await _playlistManager.RemoveFromShares(playlistId, callingUserId, share).ConfigureAwait(false);

        return NoContent();
    }

    /// <summary>
    /// Adds items to a playlist.
    /// </summary>
    /// <param name="playlistId">The playlist id.</param>
    /// <param name="ids">Item id, comma delimited.</param>
    /// <param name="userId">The userId.</param>
    /// <response code="204">Items added to playlist.</response>
    /// <returns>An <see cref="NoContentResult"/> on success.</returns>
    [HttpPost("{playlistId}/Items")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task<ActionResult> AddToPlaylist(
        [FromRoute, Required] Guid playlistId,
        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
        [FromQuery] Guid? userId)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        await _playlistManager.AddToPlaylistAsync(playlistId, ids, userId.Value).ConfigureAwait(false);
        return NoContent();
    }

    /// <summary>
    /// Moves a playlist item.
    /// </summary>
    /// <param name="playlistId">The playlist id.</param>
    /// <param name="itemId">The item id.</param>
    /// <param name="newIndex">The new index.</param>
    /// <response code="204">Item moved to new index.</response>
    /// <returns>An <see cref="NoContentResult"/> on success.</returns>
    [HttpPost("{playlistId}/Items/{itemId}/Move/{newIndex}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task<ActionResult> MoveItem(
        [FromRoute, Required] string playlistId,
        [FromRoute, Required] string itemId,
        [FromRoute, Required] int newIndex)
    {
        await _playlistManager.MoveItemAsync(playlistId, itemId, newIndex).ConfigureAwait(false);
        return NoContent();
    }

    /// <summary>
    /// Removes items from a playlist.
    /// </summary>
    /// <param name="playlistId">The playlist id.</param>
    /// <param name="entryIds">The item ids, comma delimited.</param>
    /// <response code="204">Items removed.</response>
    /// <returns>An <see cref="NoContentResult"/> on success.</returns>
    [HttpDelete("{playlistId}/Items")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task<ActionResult> RemoveFromPlaylist(
        [FromRoute, Required] string playlistId,
        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] entryIds)
    {
        await _playlistManager.RemoveFromPlaylistAsync(playlistId, entryIds).ConfigureAwait(false);
        return NoContent();
    }

    /// <summary>
    /// Gets the original items of a playlist.
    /// </summary>
    /// <param name="playlistId">The playlist id.</param>
    /// <param name="userId">User id.</param>
    /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
    /// <param name="limit">Optional. The maximum number of records to return.</param>
    /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
    /// <param name="enableImages">Optional. Include image information in output.</param>
    /// <param name="enableUserData">Optional. Include user data.</param>
    /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
    /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
    /// <response code="200">Original playlist returned.</response>
    /// <response code="404">Playlist not found.</response>
    /// <returns>The original playlist items.</returns>
    [HttpGet("{playlistId}/Items")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public ActionResult<QueryResult<BaseItemDto>> GetPlaylistItems(
        [FromRoute, Required] Guid playlistId,
        [FromQuery] Guid? userId,
        [FromQuery] int? startIndex,
        [FromQuery] int? limit,
        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
        [FromQuery] bool? enableImages,
        [FromQuery] bool? enableUserData,
        [FromQuery] int? imageTypeLimit,
        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var playlist = (Playlist)_libraryManager.GetItemById(playlistId);
        if (playlist is null)
        {
            return NotFound();
        }

        var user = userId.IsNullOrEmpty()
            ? null
            : _userManager.GetUserById(userId.Value);

        var items = playlist.GetManageableItems().ToArray();
        var count = items.Length;
        if (startIndex.HasValue)
        {
            items = items.Skip(startIndex.Value).ToArray();
        }

        if (limit.HasValue)
        {
            items = items.Take(limit.Value).ToArray();
        }

        var dtoOptions = new DtoOptions { Fields = fields }
            .AddClientFields(User)
            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);

        var dtos = _dtoService.GetBaseItemDtos(items.Select(i => i.Item2).ToList(), dtoOptions, user);
        for (int index = 0; index < dtos.Count; index++)
        {
            dtos[index].PlaylistItemId = items[index].Item1.Id;
        }

        var result = new QueryResult<BaseItemDto>(
            startIndex,
            count,
            dtos);

        return result;
    }
}