2020-11-21 14:26:03 +01:00
using System ;
2020-09-06 01:11:44 +02:00
using System.ComponentModel.DataAnnotations ;
2020-06-27 05:04:02 +02:00
using System.Diagnostics.CodeAnalysis ;
using System.Threading.Tasks ;
using Jellyfin.Api.Constants ;
2022-10-06 13:57:47 +02:00
using Jellyfin.Api.Extensions ;
2020-06-27 05:04:02 +02:00
using Jellyfin.Api.Helpers ;
2020-11-20 18:22:40 +01:00
using Jellyfin.Api.ModelBinders ;
2020-06-27 05:04:02 +02:00
using Jellyfin.Data.Entities ;
2023-02-01 19:17:18 +01:00
using MediaBrowser.Controller.Entities ;
2020-06-27 05:04:02 +02:00
using MediaBrowser.Controller.Library ;
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
{
/// <summary>
/// Playstate controller.
/// </summary>
2020-08-04 20:48:53 +02:00
[Route("")]
2020-06-27 05:04:02 +02:00
[Authorize(Policy = Policies.DefaultAuthorization)]
public class PlaystateController : BaseJellyfinApiController
{
private readonly IUserManager _userManager ;
private readonly IUserDataManager _userDataRepository ;
private readonly ILibraryManager _libraryManager ;
private readonly ISessionManager _sessionManager ;
private readonly ILogger < PlaystateController > _logger ;
private readonly TranscodingJobHelper _transcodingJobHelper ;
/// <summary>
/// Initializes a new instance of the <see cref="PlaystateController"/> class.
/// </summary>
/// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
/// <param name="userDataRepository">Instance of the <see cref="IUserDataManager"/> interface.</param>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
/// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
/// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
2020-07-12 11:14:38 +02:00
/// <param name="transcodingJobHelper">Th <see cref="TranscodingJobHelper"/> singleton.</param>
2020-06-27 05:04:02 +02:00
public PlaystateController (
IUserManager userManager ,
IUserDataManager userDataRepository ,
ILibraryManager libraryManager ,
ISessionManager sessionManager ,
ILoggerFactory loggerFactory ,
2020-07-12 11:14:38 +02:00
TranscodingJobHelper transcodingJobHelper )
2020-06-27 05:04:02 +02:00
{
_userManager = userManager ;
_userDataRepository = userDataRepository ;
_libraryManager = libraryManager ;
_sessionManager = sessionManager ;
_logger = loggerFactory . CreateLogger < PlaystateController > ( ) ;
2020-07-12 11:14:38 +02:00
_transcodingJobHelper = transcodingJobHelper ;
2020-06-27 05:04:02 +02:00
}
/// <summary>
/// Marks an item as played for user.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <param name="datePlayed">Optional. The date the item was played.</param>
/// <response code="200">Item marked as played.</response>
2023-02-01 19:17:18 +01:00
/// <response code="404">Item not found.</response>
/// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>, or a <see cref="NotFoundResult"/> if item was not found.</returns>
2020-08-04 20:48:53 +02:00
[HttpPost("Users/{userId}/PlayedItems/{itemId}")]
2020-06-27 05:04:02 +02:00
[ProducesResponseType(StatusCodes.Status200OK)]
2023-02-01 19:17:18 +01:00
[ProducesResponseType(StatusCodes.Status404NotFound)]
2021-04-10 22:57:25 +02:00
public async Task < ActionResult < UserItemDataDto > > MarkPlayedItem (
2020-09-06 17:07:27 +02:00
[FromRoute, Required] Guid userId ,
[FromRoute, Required] Guid itemId ,
2020-11-20 18:22:40 +01:00
[FromQuery, ModelBinder(typeof(LegacyDateTimeModelBinder))] DateTime ? datePlayed )
2020-06-27 05:04:02 +02:00
{
var user = _userManager . GetUserById ( userId ) ;
2022-10-06 13:57:47 +02:00
var session = await RequestHelpers . GetSession ( _sessionManager , _userManager , HttpContext ) . ConfigureAwait ( false ) ;
2023-02-01 19:17:18 +01:00
var item = _libraryManager . GetItemById ( itemId ) ;
if ( item is null )
{
return NotFound ( ) ;
}
var dto = UpdatePlayedStatus ( user , item , true , datePlayed ) ;
2020-06-27 05:04:02 +02:00
foreach ( var additionalUserInfo in session . AdditionalUsers )
{
var additionalUser = _userManager . GetUserById ( additionalUserInfo . UserId ) ;
2023-02-01 19:17:18 +01:00
UpdatePlayedStatus ( additionalUser , item , true , datePlayed ) ;
2020-06-27 05:04:02 +02:00
}
return dto ;
}
/// <summary>
/// Marks an item as unplayed for user.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <response code="200">Item marked as unplayed.</response>
2023-02-01 19:17:18 +01:00
/// <response code="404">Item not found.</response>
/// <returns>A <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>, or a <see cref="NotFoundResult"/> if item was not found.</returns>
2020-08-10 19:38:02 +02:00
[HttpDelete("Users/{userId}/PlayedItems/{itemId}")]
2020-06-27 05:04:02 +02:00
[ProducesResponseType(StatusCodes.Status200OK)]
2023-02-01 19:17:18 +01:00
[ProducesResponseType(StatusCodes.Status404NotFound)]
2021-04-10 22:57:25 +02:00
public async Task < ActionResult < UserItemDataDto > > MarkUnplayedItem ( [ FromRoute , Required ] Guid userId , [ FromRoute , Required ] Guid itemId )
2020-06-27 05:04:02 +02:00
{
var user = _userManager . GetUserById ( userId ) ;
2022-10-06 13:57:47 +02:00
var session = await RequestHelpers . GetSession ( _sessionManager , _userManager , HttpContext ) . ConfigureAwait ( false ) ;
2023-02-01 19:17:18 +01:00
var item = _libraryManager . GetItemById ( itemId ) ;
if ( item is null )
{
return NotFound ( ) ;
}
var dto = UpdatePlayedStatus ( user , item , false , null ) ;
2020-06-27 05:04:02 +02:00
foreach ( var additionalUserInfo in session . AdditionalUsers )
{
var additionalUser = _userManager . GetUserById ( additionalUserInfo . UserId ) ;
2023-02-01 19:17:18 +01:00
UpdatePlayedStatus ( additionalUser , item , false , null ) ;
2020-06-27 05:04:02 +02:00
}
return dto ;
}
/// <summary>
/// Reports playback has started within a session.
/// </summary>
/// <param name="playbackStartInfo">The playback start info.</param>
/// <response code="204">Playback start recorded.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
2020-08-04 20:48:53 +02:00
[HttpPost("Sessions/Playing")]
2020-06-27 05:04:02 +02:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task < ActionResult > ReportPlaybackStart ( [ FromBody ] PlaybackStartInfo playbackStartInfo )
{
playbackStartInfo . PlayMethod = ValidatePlayMethod ( playbackStartInfo . PlayMethod , playbackStartInfo . PlaySessionId ) ;
2022-10-06 13:57:47 +02:00
playbackStartInfo . SessionId = await RequestHelpers . GetSessionId ( _sessionManager , _userManager , HttpContext ) . ConfigureAwait ( false ) ;
2020-06-27 05:04:02 +02:00
await _sessionManager . OnPlaybackStart ( playbackStartInfo ) . ConfigureAwait ( false ) ;
return NoContent ( ) ;
}
/// <summary>
/// Reports playback progress within a session.
/// </summary>
/// <param name="playbackProgressInfo">The playback progress info.</param>
/// <response code="204">Playback progress recorded.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
2020-08-04 20:48:53 +02:00
[HttpPost("Sessions/Playing/Progress")]
2020-06-27 05:04:02 +02:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task < ActionResult > ReportPlaybackProgress ( [ FromBody ] PlaybackProgressInfo playbackProgressInfo )
{
playbackProgressInfo . PlayMethod = ValidatePlayMethod ( playbackProgressInfo . PlayMethod , playbackProgressInfo . PlaySessionId ) ;
2022-10-06 13:57:47 +02:00
playbackProgressInfo . SessionId = await RequestHelpers . GetSessionId ( _sessionManager , _userManager , HttpContext ) . ConfigureAwait ( false ) ;
2020-06-27 05:04:02 +02:00
await _sessionManager . OnPlaybackProgress ( playbackProgressInfo ) . ConfigureAwait ( false ) ;
return NoContent ( ) ;
}
/// <summary>
/// Pings a playback session.
/// </summary>
/// <param name="playSessionId">Playback session id.</param>
/// <response code="204">Playback session pinged.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
2020-08-04 20:48:53 +02:00
[HttpPost("Sessions/Playing/Ping")]
2020-06-27 05:04:02 +02:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
2021-03-05 02:25:52 +01:00
public ActionResult PingPlaybackSession ( [ FromQuery , Required ] string playSessionId )
2020-06-27 05:04:02 +02:00
{
_transcodingJobHelper . PingTranscodingJob ( playSessionId , null ) ;
return NoContent ( ) ;
}
/// <summary>
/// Reports playback has stopped within a session.
/// </summary>
/// <param name="playbackStopInfo">The playback stop info.</param>
/// <response code="204">Playback stop recorded.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
2020-08-04 20:48:53 +02:00
[HttpPost("Sessions/Playing/Stopped")]
2020-06-27 05:04:02 +02:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task < ActionResult > ReportPlaybackStopped ( [ FromBody ] PlaybackStopInfo playbackStopInfo )
{
_logger . LogDebug ( "ReportPlaybackStopped PlaySessionId: {0}" , playbackStopInfo . PlaySessionId ? ? string . Empty ) ;
if ( ! string . IsNullOrWhiteSpace ( playbackStopInfo . PlaySessionId ) )
{
2022-10-06 13:57:47 +02:00
await _transcodingJobHelper . KillTranscodingJobs ( User . GetDeviceId ( ) ! , playbackStopInfo . PlaySessionId , s = > true ) . ConfigureAwait ( false ) ;
2020-06-27 05:04:02 +02:00
}
2022-10-06 13:57:47 +02:00
playbackStopInfo . SessionId = await RequestHelpers . GetSessionId ( _sessionManager , _userManager , HttpContext ) . ConfigureAwait ( false ) ;
2020-06-27 05:04:02 +02:00
await _sessionManager . OnPlaybackStopped ( playbackStopInfo ) . ConfigureAwait ( false ) ;
return NoContent ( ) ;
}
/// <summary>
/// Reports that a user has begun playing an item.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <param name="mediaSourceId">The id of the MediaSource.</param>
/// <param name="audioStreamIndex">The audio stream index.</param>
/// <param name="subtitleStreamIndex">The subtitle stream index.</param>
/// <param name="playMethod">The play method.</param>
/// <param name="liveStreamId">The live stream id.</param>
/// <param name="playSessionId">The play session id.</param>
2020-07-07 17:10:51 +02:00
/// <param name="canSeek">Indicates if the client can seek.</param>
2020-06-27 05:04:02 +02:00
/// <response code="204">Play start recorded.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
2020-08-04 20:48:53 +02:00
[HttpPost("Users/{userId}/PlayingItems/{itemId}")]
2020-06-27 05:04:02 +02:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
public async Task < ActionResult > OnPlaybackStart (
2020-09-06 17:07:27 +02:00
[FromRoute, Required] Guid userId ,
[FromRoute, Required] Guid itemId ,
2020-07-07 17:10:51 +02:00
[FromQuery] string? mediaSourceId ,
2020-06-27 05:04:02 +02:00
[FromQuery] int? audioStreamIndex ,
[FromQuery] int? subtitleStreamIndex ,
2021-03-05 02:25:52 +01:00
[FromQuery] PlayMethod ? playMethod ,
2020-07-07 17:10:51 +02:00
[FromQuery] string? liveStreamId ,
2021-03-05 02:25:52 +01:00
[FromQuery] string? playSessionId ,
2020-07-07 17:10:51 +02:00
[FromQuery] bool canSeek = false )
2020-06-27 05:04:02 +02:00
{
var playbackStartInfo = new PlaybackStartInfo
{
CanSeek = canSeek ,
ItemId = itemId ,
MediaSourceId = mediaSourceId ,
AudioStreamIndex = audioStreamIndex ,
SubtitleStreamIndex = subtitleStreamIndex ,
2021-03-05 02:25:52 +01:00
PlayMethod = playMethod ? ? PlayMethod . Transcode ,
2020-06-27 05:04:02 +02:00
PlaySessionId = playSessionId ,
LiveStreamId = liveStreamId
} ;
playbackStartInfo . PlayMethod = ValidatePlayMethod ( playbackStartInfo . PlayMethod , playbackStartInfo . PlaySessionId ) ;
2022-10-06 13:57:47 +02:00
playbackStartInfo . SessionId = await RequestHelpers . GetSessionId ( _sessionManager , _userManager , HttpContext ) . ConfigureAwait ( false ) ;
2020-06-27 05:04:02 +02:00
await _sessionManager . OnPlaybackStart ( playbackStartInfo ) . ConfigureAwait ( false ) ;
return NoContent ( ) ;
}
/// <summary>
/// Reports a user's playback progress.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <param name="mediaSourceId">The id of the MediaSource.</param>
/// <param name="positionTicks">Optional. The current position, in ticks. 1 tick = 10000 ms.</param>
/// <param name="audioStreamIndex">The audio stream index.</param>
/// <param name="subtitleStreamIndex">The subtitle stream index.</param>
/// <param name="volumeLevel">Scale of 0-100.</param>
/// <param name="playMethod">The play method.</param>
/// <param name="liveStreamId">The live stream id.</param>
/// <param name="playSessionId">The play session id.</param>
/// <param name="repeatMode">The repeat mode.</param>
2020-07-07 17:10:51 +02:00
/// <param name="isPaused">Indicates if the player is paused.</param>
/// <param name="isMuted">Indicates if the player is muted.</param>
2020-06-27 05:04:02 +02:00
/// <response code="204">Play progress recorded.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
2020-08-04 20:48:53 +02:00
[HttpPost("Users/{userId}/PlayingItems/{itemId}/Progress")]
2020-06-27 05:04:02 +02:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
public async Task < ActionResult > OnPlaybackProgress (
2020-09-06 17:07:27 +02:00
[FromRoute, Required] Guid userId ,
[FromRoute, Required] Guid itemId ,
2020-07-07 17:10:51 +02:00
[FromQuery] string? mediaSourceId ,
2020-06-27 05:04:02 +02:00
[FromQuery] long? positionTicks ,
[FromQuery] int? audioStreamIndex ,
[FromQuery] int? subtitleStreamIndex ,
[FromQuery] int? volumeLevel ,
2021-03-05 02:25:52 +01:00
[FromQuery] PlayMethod ? playMethod ,
2020-07-07 17:10:51 +02:00
[FromQuery] string? liveStreamId ,
2021-03-05 02:25:52 +01:00
[FromQuery] string? playSessionId ,
[FromQuery] RepeatMode ? repeatMode ,
2020-07-07 17:10:51 +02:00
[FromQuery] bool isPaused = false ,
[FromQuery] bool isMuted = false )
2020-06-27 05:04:02 +02:00
{
var playbackProgressInfo = new PlaybackProgressInfo
{
ItemId = itemId ,
PositionTicks = positionTicks ,
IsMuted = isMuted ,
IsPaused = isPaused ,
MediaSourceId = mediaSourceId ,
AudioStreamIndex = audioStreamIndex ,
SubtitleStreamIndex = subtitleStreamIndex ,
VolumeLevel = volumeLevel ,
2021-03-05 02:25:52 +01:00
PlayMethod = playMethod ? ? PlayMethod . Transcode ,
2020-06-27 05:04:02 +02:00
PlaySessionId = playSessionId ,
LiveStreamId = liveStreamId ,
2021-03-05 02:25:52 +01:00
RepeatMode = repeatMode ? ? RepeatMode . RepeatNone
2020-06-27 05:04:02 +02:00
} ;
playbackProgressInfo . PlayMethod = ValidatePlayMethod ( playbackProgressInfo . PlayMethod , playbackProgressInfo . PlaySessionId ) ;
2022-10-11 23:37:29 +02:00
playbackProgressInfo . SessionId = await RequestHelpers . GetSessionId ( _sessionManager , _userManager , HttpContext ) . ConfigureAwait ( false ) ;
2020-06-27 05:04:02 +02:00
await _sessionManager . OnPlaybackProgress ( playbackProgressInfo ) . ConfigureAwait ( false ) ;
return NoContent ( ) ;
}
/// <summary>
/// Reports that a user has stopped playing an item.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <param name="mediaSourceId">The id of the MediaSource.</param>
/// <param name="nextMediaType">The next media type that will play.</param>
/// <param name="positionTicks">Optional. The position, in ticks, where playback stopped. 1 tick = 10000 ms.</param>
/// <param name="liveStreamId">The live stream id.</param>
/// <param name="playSessionId">The play session id.</param>
/// <response code="204">Playback stop recorded.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
2020-08-04 20:48:53 +02:00
[HttpDelete("Users/{userId}/PlayingItems/{itemId}")]
2020-06-27 05:04:02 +02:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
public async Task < ActionResult > OnPlaybackStopped (
2020-09-06 17:07:27 +02:00
[FromRoute, Required] Guid userId ,
[FromRoute, Required] Guid itemId ,
2020-07-07 17:10:51 +02:00
[FromQuery] string? mediaSourceId ,
[FromQuery] string? nextMediaType ,
2020-06-27 05:04:02 +02:00
[FromQuery] long? positionTicks ,
2020-07-07 17:10:51 +02:00
[FromQuery] string? liveStreamId ,
[FromQuery] string? playSessionId )
2020-06-27 05:04:02 +02:00
{
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 ) )
{
2022-10-06 13:57:47 +02:00
await _transcodingJobHelper . KillTranscodingJobs ( User . GetDeviceId ( ) ! , playbackStopInfo . PlaySessionId , s = > true ) . ConfigureAwait ( false ) ;
2020-06-27 05:04:02 +02:00
}
2022-10-11 23:37:29 +02:00
playbackStopInfo . SessionId = await RequestHelpers . GetSessionId ( _sessionManager , _userManager , HttpContext ) . ConfigureAwait ( false ) ;
2020-06-27 05:04:02 +02:00
await _sessionManager . OnPlaybackStopped ( playbackStopInfo ) . ConfigureAwait ( false ) ;
return NoContent ( ) ;
}
/// <summary>
/// Updates the played status.
/// </summary>
/// <param name="user">The user.</param>
2023-02-01 19:17:18 +01:00
/// <param name="item">The item.</param>
2020-06-27 05:04:02 +02:00
/// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
/// <param name="datePlayed">The date played.</param>
/// <returns>Task.</returns>
2023-02-01 19:17:18 +01:00
private UserItemDataDto UpdatePlayedStatus ( User user , BaseItem item , bool wasPlayed , DateTime ? datePlayed )
2020-06-27 05:04:02 +02:00
{
if ( wasPlayed )
{
item . MarkPlayed ( user , datePlayed , true ) ;
}
else
{
item . MarkUnplayed ( user ) ;
}
return _userDataRepository . GetUserDataDto ( item , user ) ;
}
2021-03-05 02:25:52 +01:00
private PlayMethod ValidatePlayMethod ( PlayMethod method , string? playSessionId )
2020-06-27 05:04:02 +02:00
{
if ( method = = PlayMethod . Transcode )
{
var job = string . IsNullOrWhiteSpace ( playSessionId ) ? null : _transcodingJobHelper . GetTranscodingJob ( playSessionId ) ;
2022-12-05 15:00:20 +01:00
if ( job is null )
2020-06-27 05:04:02 +02:00
{
return PlayMethod . DirectPlay ;
}
}
return method ;
}
}
}