using System; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using Jellyfin.Extensions; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Session; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace Jellyfin.Api.Controllers; /// /// Playstate controller. /// [Route("")] [Authorize] public class PlaystateController : BaseJellyfinApiController { private readonly IUserManager _userManager; private readonly IUserDataManager _userDataRepository; private readonly ILibraryManager _libraryManager; private readonly ISessionManager _sessionManager; private readonly ILogger _logger; private readonly ITranscodeManager _transcodeManager; /// /// Initializes a new instance of the class. /// /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. public PlaystateController( IUserManager userManager, IUserDataManager userDataRepository, ILibraryManager libraryManager, ISessionManager sessionManager, ILoggerFactory loggerFactory, ITranscodeManager transcodeManager) { _userManager = userManager; _userDataRepository = userDataRepository; _libraryManager = libraryManager; _sessionManager = sessionManager; _logger = loggerFactory.CreateLogger(); _transcodeManager = transcodeManager; } /// /// Marks an item as played for user. /// /// User id. /// Item id. /// Optional. The date the item was played. /// Item marked as played. /// Item not found. /// An containing the , or a if item was not found. [HttpPost("UserPlayedItems/{itemId}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task> MarkPlayedItem( [FromQuery] Guid? userId, [FromRoute, Required] Guid itemId, [FromQuery, ModelBinder(typeof(LegacyDateTimeModelBinder))] DateTime? datePlayed) { userId = RequestHelpers.GetUserId(User, userId); var user = _userManager.GetUserById(userId.Value); if (user is null) { return NotFound(); } var item = _libraryManager.GetItemById(itemId, user); if (item is null) { return NotFound(); } var session = await RequestHelpers.GetSession(_sessionManager, _userManager, HttpContext, userId).ConfigureAwait(false); var dto = UpdatePlayedStatus(user, item, true, datePlayed); foreach (var additionalUserInfo in session.AdditionalUsers) { var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId); if (additionalUser is null) { return NotFound(); } UpdatePlayedStatus(additionalUser, item, true, datePlayed); } return dto; } /// /// Marks an item as played for user. /// /// User id. /// Item id. /// Optional. The date the item was played. /// Item marked as played. /// Item not found. /// An containing the , or a if item was not found. [HttpPost("Users/{userId}/PlayedItems/{itemId}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [Obsolete("Kept for backwards compatibility")] [ApiExplorerSettings(IgnoreApi = true)] public Task> MarkPlayedItemLegacy( [FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId, [FromQuery, ModelBinder(typeof(LegacyDateTimeModelBinder))] DateTime? datePlayed) => MarkPlayedItem(userId, itemId, datePlayed); /// /// Marks an item as unplayed for user. /// /// User id. /// Item id. /// Item marked as unplayed. /// Item not found. /// A containing the , or a if item was not found. [HttpDelete("UserPlayedItems/{itemId}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task> MarkUnplayedItem( [FromQuery] Guid? userId, [FromRoute, Required] Guid itemId) { userId = RequestHelpers.GetUserId(User, userId); var user = _userManager.GetUserById(userId.Value); if (user is null) { return NotFound(); } var item = _libraryManager.GetItemById(itemId, user); if (item is null) { return NotFound(); } var session = await RequestHelpers.GetSession(_sessionManager, _userManager, HttpContext, userId).ConfigureAwait(false); var dto = UpdatePlayedStatus(user, item, false, null); foreach (var additionalUserInfo in session.AdditionalUsers) { var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId); if (additionalUser is null) { return NotFound(); } UpdatePlayedStatus(additionalUser, item, false, null); } return dto; } /// /// Marks an item as unplayed for user. /// /// User id. /// Item id. /// Item marked as unplayed. /// Item not found. /// A containing the , or a if item was not found. [HttpDelete("Users/{userId}/PlayedItems/{itemId}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [Obsolete("Kept for backwards compatibility")] [ApiExplorerSettings(IgnoreApi = true)] public Task> MarkUnplayedItemLegacy( [FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId) => MarkUnplayedItem(userId, itemId); /// /// Reports playback has started within a session. /// /// The playback start info. /// Playback start recorded. /// A . [HttpPost("Sessions/Playing")] [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task ReportPlaybackStart([FromBody] PlaybackStartInfo playbackStartInfo) { playbackStartInfo.PlayMethod = ValidatePlayMethod(playbackStartInfo.PlayMethod, playbackStartInfo.PlaySessionId); playbackStartInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false); await _sessionManager.OnPlaybackStart(playbackStartInfo).ConfigureAwait(false); return NoContent(); } /// /// Reports playback progress within a session. /// /// The playback progress info. /// Playback progress recorded. /// A . [HttpPost("Sessions/Playing/Progress")] [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task ReportPlaybackProgress([FromBody] PlaybackProgressInfo playbackProgressInfo) { playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId); playbackProgressInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false); await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false); return NoContent(); } /// /// Pings a playback session. /// /// Playback session id. /// Playback session pinged. /// A . [HttpPost("Sessions/Playing/Ping")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult PingPlaybackSession([FromQuery, Required] string playSessionId) { _transcodeManager.PingTranscodingJob(playSessionId, null); return NoContent(); } /// /// Reports playback has stopped within a session. /// /// The playback stop info. /// Playback stop recorded. /// A . [HttpPost("Sessions/Playing/Stopped")] [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task ReportPlaybackStopped([FromBody] PlaybackStopInfo playbackStopInfo) { _logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", playbackStopInfo.PlaySessionId ?? string.Empty); if (!string.IsNullOrWhiteSpace(playbackStopInfo.PlaySessionId)) { await _transcodeManager.KillTranscodingJobs(User.GetDeviceId()!, playbackStopInfo.PlaySessionId, s => true).ConfigureAwait(false); } playbackStopInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false); await _sessionManager.OnPlaybackStopped(playbackStopInfo).ConfigureAwait(false); return NoContent(); } /// /// Reports that a session has begun playing an item. /// /// Item id. /// The id of the MediaSource. /// The audio stream index. /// The subtitle stream index. /// The play method. /// The live stream id. /// The play session id. /// Indicates if the client can seek. /// Play start recorded. /// A . [HttpPost("PlayingItems/{itemId}")] [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task OnPlaybackStart( [FromRoute, Required] Guid itemId, [FromQuery] string? mediaSourceId, [FromQuery] int? audioStreamIndex, [FromQuery] int? subtitleStreamIndex, [FromQuery] PlayMethod? playMethod, [FromQuery] string? liveStreamId, [FromQuery] string? playSessionId, [FromQuery] bool canSeek = false) { var playbackStartInfo = new PlaybackStartInfo { CanSeek = canSeek, ItemId = itemId, MediaSourceId = mediaSourceId, AudioStreamIndex = audioStreamIndex, SubtitleStreamIndex = subtitleStreamIndex, PlayMethod = playMethod ?? PlayMethod.Transcode, PlaySessionId = playSessionId, LiveStreamId = liveStreamId }; playbackStartInfo.PlayMethod = ValidatePlayMethod(playbackStartInfo.PlayMethod, playbackStartInfo.PlaySessionId); playbackStartInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false); await _sessionManager.OnPlaybackStart(playbackStartInfo).ConfigureAwait(false); return NoContent(); } /// /// Reports that a user has begun playing an item. /// /// User id. /// Item id. /// The id of the MediaSource. /// The audio stream index. /// The subtitle stream index. /// The play method. /// The live stream id. /// The play session id. /// Indicates if the client can seek. /// Play start recorded. /// A . [HttpPost("Users/{userId}/PlayingItems/{itemId}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [Obsolete("Kept for backwards compatibility")] [ApiExplorerSettings(IgnoreApi = true)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")] public Task OnPlaybackStartLegacy( [FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId, [FromQuery] string? mediaSourceId, [FromQuery] int? audioStreamIndex, [FromQuery] int? subtitleStreamIndex, [FromQuery] PlayMethod? playMethod, [FromQuery] string? liveStreamId, [FromQuery] string? playSessionId, [FromQuery] bool canSeek = false) => OnPlaybackStart(itemId, mediaSourceId, audioStreamIndex, subtitleStreamIndex, playMethod, liveStreamId, playSessionId, canSeek); /// /// Reports a session's playback progress. /// /// Item id. /// The id of the MediaSource. /// Optional. The current position, in ticks. 1 tick = 10000 ms. /// The audio stream index. /// The subtitle stream index. /// Scale of 0-100. /// The play method. /// The live stream id. /// The play session id. /// The repeat mode. /// Indicates if the player is paused. /// Indicates if the player is muted. /// Play progress recorded. /// A . [HttpPost("PlayingItems/{itemId}/Progress")] [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task OnPlaybackProgress( [FromRoute, Required] Guid itemId, [FromQuery] string? mediaSourceId, [FromQuery] long? positionTicks, [FromQuery] int? audioStreamIndex, [FromQuery] int? subtitleStreamIndex, [FromQuery] int? volumeLevel, [FromQuery] PlayMethod? playMethod, [FromQuery] string? liveStreamId, [FromQuery] string? playSessionId, [FromQuery] RepeatMode? repeatMode, [FromQuery] bool isPaused = false, [FromQuery] bool isMuted = false) { var playbackProgressInfo = new PlaybackProgressInfo { ItemId = itemId, PositionTicks = positionTicks, IsMuted = isMuted, IsPaused = isPaused, MediaSourceId = mediaSourceId, AudioStreamIndex = audioStreamIndex, SubtitleStreamIndex = subtitleStreamIndex, VolumeLevel = volumeLevel, PlayMethod = playMethod ?? PlayMethod.Transcode, PlaySessionId = playSessionId, LiveStreamId = liveStreamId, RepeatMode = repeatMode ?? RepeatMode.RepeatNone }; playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId); playbackProgressInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false); await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false); return NoContent(); } /// /// Reports a user's playback progress. /// /// User id. /// Item id. /// The id of the MediaSource. /// Optional. The current position, in ticks. 1 tick = 10000 ms. /// The audio stream index. /// The subtitle stream index. /// Scale of 0-100. /// The play method. /// The live stream id. /// The play session id. /// The repeat mode. /// Indicates if the player is paused. /// Indicates if the player is muted. /// Play progress recorded. /// A . [HttpPost("Users/{userId}/PlayingItems/{itemId}/Progress")] [ProducesResponseType(StatusCodes.Status204NoContent)] [Obsolete("Kept for backwards compatibility")] [ApiExplorerSettings(IgnoreApi = true)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")] public Task OnPlaybackProgressLegacy( [FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId, [FromQuery] string? mediaSourceId, [FromQuery] long? positionTicks, [FromQuery] int? audioStreamIndex, [FromQuery] int? subtitleStreamIndex, [FromQuery] int? volumeLevel, [FromQuery] PlayMethod? playMethod, [FromQuery] string? liveStreamId, [FromQuery] string? playSessionId, [FromQuery] RepeatMode? repeatMode, [FromQuery] bool isPaused = false, [FromQuery] bool isMuted = false) => OnPlaybackProgress(itemId, mediaSourceId, positionTicks, audioStreamIndex, subtitleStreamIndex, volumeLevel, playMethod, liveStreamId, playSessionId, repeatMode, isPaused, isMuted); /// /// Reports that a session has stopped playing an item. /// /// Item id. /// The id of the MediaSource. /// The next media type that will play. /// Optional. The position, in ticks, where playback stopped. 1 tick = 10000 ms. /// The live stream id. /// The play session id. /// Playback stop recorded. /// A . [HttpDelete("PlayingItems/{itemId}")] [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task OnPlaybackStopped( [FromRoute, Required] Guid itemId, [FromQuery] string? mediaSourceId, [FromQuery] string? nextMediaType, [FromQuery] long? positionTicks, [FromQuery] string? liveStreamId, [FromQuery] string? playSessionId) { var playbackStopInfo = new PlaybackStopInfo { ItemId = itemId, PositionTicks = positionTicks, MediaSourceId = mediaSourceId, PlaySessionId = playSessionId, LiveStreamId = liveStreamId, NextMediaType = nextMediaType }; _logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", playbackStopInfo.PlaySessionId ?? string.Empty); if (!string.IsNullOrWhiteSpace(playbackStopInfo.PlaySessionId)) { await _transcodeManager.KillTranscodingJobs(User.GetDeviceId()!, playbackStopInfo.PlaySessionId, s => true).ConfigureAwait(false); } playbackStopInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false); await _sessionManager.OnPlaybackStopped(playbackStopInfo).ConfigureAwait(false); return NoContent(); } /// /// Reports that a user has stopped playing an item. /// /// User id. /// Item id. /// The id of the MediaSource. /// The next media type that will play. /// Optional. The position, in ticks, where playback stopped. 1 tick = 10000 ms. /// The live stream id. /// The play session id. /// Playback stop recorded. /// A . [HttpDelete("Users/{userId}/PlayingItems/{itemId}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [Obsolete("Kept for backwards compatibility")] [ApiExplorerSettings(IgnoreApi = true)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")] public Task OnPlaybackStoppedLegacy( [FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId, [FromQuery] string? mediaSourceId, [FromQuery] string? nextMediaType, [FromQuery] long? positionTicks, [FromQuery] string? liveStreamId, [FromQuery] string? playSessionId) => OnPlaybackStopped(itemId, mediaSourceId, nextMediaType, positionTicks, liveStreamId, playSessionId); /// /// Updates the played status. /// /// The user. /// The item. /// if set to true [was played]. /// The date played. /// Task. private UserItemDataDto UpdatePlayedStatus(User user, BaseItem item, bool wasPlayed, DateTime? datePlayed) { if (wasPlayed) { item.MarkPlayed(user, datePlayed, true); } else { item.MarkUnplayed(user); } return _userDataRepository.GetUserDataDto(item, user); } private PlayMethod ValidatePlayMethod(PlayMethod method, string? playSessionId) { if (method == PlayMethod.Transcode) { var job = string.IsNullOrWhiteSpace(playSessionId) ? null : _transcodeManager.GetTranscodingJob(playSessionId); if (job is null) { return PlayMethod.DirectPlay; } } return method; } }