PlaystateController.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Threading.Tasks;
  5. using Jellyfin.Api.Extensions;
  6. using Jellyfin.Api.Helpers;
  7. using Jellyfin.Api.ModelBinders;
  8. using Jellyfin.Data.Entities;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Session;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Session;
  14. using Microsoft.AspNetCore.Authorization;
  15. using Microsoft.AspNetCore.Http;
  16. using Microsoft.AspNetCore.Mvc;
  17. using Microsoft.Extensions.Logging;
  18. namespace Jellyfin.Api.Controllers;
  19. /// <summary>
  20. /// Playstate controller.
  21. /// </summary>
  22. [Route("")]
  23. [Authorize]
  24. public class PlaystateController : BaseJellyfinApiController
  25. {
  26. private readonly IUserManager _userManager;
  27. private readonly IUserDataManager _userDataRepository;
  28. private readonly ILibraryManager _libraryManager;
  29. private readonly ISessionManager _sessionManager;
  30. private readonly ILogger<PlaystateController> _logger;
  31. private readonly TranscodingJobHelper _transcodingJobHelper;
  32. /// <summary>
  33. /// Initializes a new instance of the <see cref="PlaystateController"/> class.
  34. /// </summary>
  35. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  36. /// <param name="userDataRepository">Instance of the <see cref="IUserDataManager"/> interface.</param>
  37. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  38. /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
  39. /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
  40. /// <param name="transcodingJobHelper">Th <see cref="TranscodingJobHelper"/> singleton.</param>
  41. public PlaystateController(
  42. IUserManager userManager,
  43. IUserDataManager userDataRepository,
  44. ILibraryManager libraryManager,
  45. ISessionManager sessionManager,
  46. ILoggerFactory loggerFactory,
  47. TranscodingJobHelper transcodingJobHelper)
  48. {
  49. _userManager = userManager;
  50. _userDataRepository = userDataRepository;
  51. _libraryManager = libraryManager;
  52. _sessionManager = sessionManager;
  53. _logger = loggerFactory.CreateLogger<PlaystateController>();
  54. _transcodingJobHelper = transcodingJobHelper;
  55. }
  56. /// <summary>
  57. /// Marks an item as played for user.
  58. /// </summary>
  59. /// <param name="userId">User id.</param>
  60. /// <param name="itemId">Item id.</param>
  61. /// <param name="datePlayed">Optional. The date the item was played.</param>
  62. /// <response code="200">Item marked as played.</response>
  63. /// <response code="404">Item not found.</response>
  64. /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>, or a <see cref="NotFoundResult"/> if item was not found.</returns>
  65. [HttpPost("Users/{userId}/PlayedItems/{itemId}")]
  66. [ProducesResponseType(StatusCodes.Status200OK)]
  67. [ProducesResponseType(StatusCodes.Status404NotFound)]
  68. public async Task<ActionResult<UserItemDataDto>> MarkPlayedItem(
  69. [FromRoute, Required] Guid userId,
  70. [FromRoute, Required] Guid itemId,
  71. [FromQuery, ModelBinder(typeof(LegacyDateTimeModelBinder))] DateTime? datePlayed)
  72. {
  73. var user = _userManager.GetUserById(userId);
  74. if (user is null)
  75. {
  76. return NotFound();
  77. }
  78. var session = await RequestHelpers.GetSession(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  79. var item = _libraryManager.GetItemById(itemId);
  80. if (item is null)
  81. {
  82. return NotFound();
  83. }
  84. var dto = UpdatePlayedStatus(user, item, true, datePlayed);
  85. foreach (var additionalUserInfo in session.AdditionalUsers)
  86. {
  87. var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
  88. if (additionalUser is null)
  89. {
  90. return NotFound();
  91. }
  92. UpdatePlayedStatus(additionalUser, item, true, datePlayed);
  93. }
  94. return dto;
  95. }
  96. /// <summary>
  97. /// Marks an item as unplayed for user.
  98. /// </summary>
  99. /// <param name="userId">User id.</param>
  100. /// <param name="itemId">Item id.</param>
  101. /// <response code="200">Item marked as unplayed.</response>
  102. /// <response code="404">Item not found.</response>
  103. /// <returns>A <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>, or a <see cref="NotFoundResult"/> if item was not found.</returns>
  104. [HttpDelete("Users/{userId}/PlayedItems/{itemId}")]
  105. [ProducesResponseType(StatusCodes.Status200OK)]
  106. [ProducesResponseType(StatusCodes.Status404NotFound)]
  107. public async Task<ActionResult<UserItemDataDto>> MarkUnplayedItem([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
  108. {
  109. var user = _userManager.GetUserById(userId);
  110. if (user is null)
  111. {
  112. return NotFound();
  113. }
  114. var session = await RequestHelpers.GetSession(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  115. var item = _libraryManager.GetItemById(itemId);
  116. if (item is null)
  117. {
  118. return NotFound();
  119. }
  120. var dto = UpdatePlayedStatus(user, item, false, null);
  121. foreach (var additionalUserInfo in session.AdditionalUsers)
  122. {
  123. var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
  124. if (additionalUser is null)
  125. {
  126. return NotFound();
  127. }
  128. UpdatePlayedStatus(additionalUser, item, false, null);
  129. }
  130. return dto;
  131. }
  132. /// <summary>
  133. /// Reports playback has started within a session.
  134. /// </summary>
  135. /// <param name="playbackStartInfo">The playback start info.</param>
  136. /// <response code="204">Playback start recorded.</response>
  137. /// <returns>A <see cref="NoContentResult"/>.</returns>
  138. [HttpPost("Sessions/Playing")]
  139. [ProducesResponseType(StatusCodes.Status204NoContent)]
  140. public async Task<ActionResult> ReportPlaybackStart([FromBody] PlaybackStartInfo playbackStartInfo)
  141. {
  142. playbackStartInfo.PlayMethod = ValidatePlayMethod(playbackStartInfo.PlayMethod, playbackStartInfo.PlaySessionId);
  143. playbackStartInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  144. await _sessionManager.OnPlaybackStart(playbackStartInfo).ConfigureAwait(false);
  145. return NoContent();
  146. }
  147. /// <summary>
  148. /// Reports playback progress within a session.
  149. /// </summary>
  150. /// <param name="playbackProgressInfo">The playback progress info.</param>
  151. /// <response code="204">Playback progress recorded.</response>
  152. /// <returns>A <see cref="NoContentResult"/>.</returns>
  153. [HttpPost("Sessions/Playing/Progress")]
  154. [ProducesResponseType(StatusCodes.Status204NoContent)]
  155. public async Task<ActionResult> ReportPlaybackProgress([FromBody] PlaybackProgressInfo playbackProgressInfo)
  156. {
  157. playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId);
  158. playbackProgressInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  159. await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false);
  160. return NoContent();
  161. }
  162. /// <summary>
  163. /// Pings a playback session.
  164. /// </summary>
  165. /// <param name="playSessionId">Playback session id.</param>
  166. /// <response code="204">Playback session pinged.</response>
  167. /// <returns>A <see cref="NoContentResult"/>.</returns>
  168. [HttpPost("Sessions/Playing/Ping")]
  169. [ProducesResponseType(StatusCodes.Status204NoContent)]
  170. public ActionResult PingPlaybackSession([FromQuery, Required] string playSessionId)
  171. {
  172. _transcodingJobHelper.PingTranscodingJob(playSessionId, null);
  173. return NoContent();
  174. }
  175. /// <summary>
  176. /// Reports playback has stopped within a session.
  177. /// </summary>
  178. /// <param name="playbackStopInfo">The playback stop info.</param>
  179. /// <response code="204">Playback stop recorded.</response>
  180. /// <returns>A <see cref="NoContentResult"/>.</returns>
  181. [HttpPost("Sessions/Playing/Stopped")]
  182. [ProducesResponseType(StatusCodes.Status204NoContent)]
  183. public async Task<ActionResult> ReportPlaybackStopped([FromBody] PlaybackStopInfo playbackStopInfo)
  184. {
  185. _logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", playbackStopInfo.PlaySessionId ?? string.Empty);
  186. if (!string.IsNullOrWhiteSpace(playbackStopInfo.PlaySessionId))
  187. {
  188. await _transcodingJobHelper.KillTranscodingJobs(User.GetDeviceId()!, playbackStopInfo.PlaySessionId, s => true).ConfigureAwait(false);
  189. }
  190. playbackStopInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  191. await _sessionManager.OnPlaybackStopped(playbackStopInfo).ConfigureAwait(false);
  192. return NoContent();
  193. }
  194. /// <summary>
  195. /// Reports that a user has begun playing an item.
  196. /// </summary>
  197. /// <param name="userId">User id.</param>
  198. /// <param name="itemId">Item id.</param>
  199. /// <param name="mediaSourceId">The id of the MediaSource.</param>
  200. /// <param name="audioStreamIndex">The audio stream index.</param>
  201. /// <param name="subtitleStreamIndex">The subtitle stream index.</param>
  202. /// <param name="playMethod">The play method.</param>
  203. /// <param name="liveStreamId">The live stream id.</param>
  204. /// <param name="playSessionId">The play session id.</param>
  205. /// <param name="canSeek">Indicates if the client can seek.</param>
  206. /// <response code="204">Play start recorded.</response>
  207. /// <returns>A <see cref="NoContentResult"/>.</returns>
  208. [HttpPost("Users/{userId}/PlayingItems/{itemId}")]
  209. [ProducesResponseType(StatusCodes.Status204NoContent)]
  210. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
  211. public async Task<ActionResult> OnPlaybackStart(
  212. [FromRoute, Required] Guid userId,
  213. [FromRoute, Required] Guid itemId,
  214. [FromQuery] string? mediaSourceId,
  215. [FromQuery] int? audioStreamIndex,
  216. [FromQuery] int? subtitleStreamIndex,
  217. [FromQuery] PlayMethod? playMethod,
  218. [FromQuery] string? liveStreamId,
  219. [FromQuery] string? playSessionId,
  220. [FromQuery] bool canSeek = false)
  221. {
  222. var playbackStartInfo = new PlaybackStartInfo
  223. {
  224. CanSeek = canSeek,
  225. ItemId = itemId,
  226. MediaSourceId = mediaSourceId,
  227. AudioStreamIndex = audioStreamIndex,
  228. SubtitleStreamIndex = subtitleStreamIndex,
  229. PlayMethod = playMethod ?? PlayMethod.Transcode,
  230. PlaySessionId = playSessionId,
  231. LiveStreamId = liveStreamId
  232. };
  233. playbackStartInfo.PlayMethod = ValidatePlayMethod(playbackStartInfo.PlayMethod, playbackStartInfo.PlaySessionId);
  234. playbackStartInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  235. await _sessionManager.OnPlaybackStart(playbackStartInfo).ConfigureAwait(false);
  236. return NoContent();
  237. }
  238. /// <summary>
  239. /// Reports a user's playback progress.
  240. /// </summary>
  241. /// <param name="userId">User id.</param>
  242. /// <param name="itemId">Item id.</param>
  243. /// <param name="mediaSourceId">The id of the MediaSource.</param>
  244. /// <param name="positionTicks">Optional. The current position, in ticks. 1 tick = 10000 ms.</param>
  245. /// <param name="audioStreamIndex">The audio stream index.</param>
  246. /// <param name="subtitleStreamIndex">The subtitle stream index.</param>
  247. /// <param name="volumeLevel">Scale of 0-100.</param>
  248. /// <param name="playMethod">The play method.</param>
  249. /// <param name="liveStreamId">The live stream id.</param>
  250. /// <param name="playSessionId">The play session id.</param>
  251. /// <param name="repeatMode">The repeat mode.</param>
  252. /// <param name="isPaused">Indicates if the player is paused.</param>
  253. /// <param name="isMuted">Indicates if the player is muted.</param>
  254. /// <response code="204">Play progress recorded.</response>
  255. /// <returns>A <see cref="NoContentResult"/>.</returns>
  256. [HttpPost("Users/{userId}/PlayingItems/{itemId}/Progress")]
  257. [ProducesResponseType(StatusCodes.Status204NoContent)]
  258. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
  259. public async Task<ActionResult> OnPlaybackProgress(
  260. [FromRoute, Required] Guid userId,
  261. [FromRoute, Required] Guid itemId,
  262. [FromQuery] string? mediaSourceId,
  263. [FromQuery] long? positionTicks,
  264. [FromQuery] int? audioStreamIndex,
  265. [FromQuery] int? subtitleStreamIndex,
  266. [FromQuery] int? volumeLevel,
  267. [FromQuery] PlayMethod? playMethod,
  268. [FromQuery] string? liveStreamId,
  269. [FromQuery] string? playSessionId,
  270. [FromQuery] RepeatMode? repeatMode,
  271. [FromQuery] bool isPaused = false,
  272. [FromQuery] bool isMuted = false)
  273. {
  274. var playbackProgressInfo = new PlaybackProgressInfo
  275. {
  276. ItemId = itemId,
  277. PositionTicks = positionTicks,
  278. IsMuted = isMuted,
  279. IsPaused = isPaused,
  280. MediaSourceId = mediaSourceId,
  281. AudioStreamIndex = audioStreamIndex,
  282. SubtitleStreamIndex = subtitleStreamIndex,
  283. VolumeLevel = volumeLevel,
  284. PlayMethod = playMethod ?? PlayMethod.Transcode,
  285. PlaySessionId = playSessionId,
  286. LiveStreamId = liveStreamId,
  287. RepeatMode = repeatMode ?? RepeatMode.RepeatNone
  288. };
  289. playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId);
  290. playbackProgressInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  291. await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false);
  292. return NoContent();
  293. }
  294. /// <summary>
  295. /// Reports that a user has stopped playing an item.
  296. /// </summary>
  297. /// <param name="userId">User id.</param>
  298. /// <param name="itemId">Item id.</param>
  299. /// <param name="mediaSourceId">The id of the MediaSource.</param>
  300. /// <param name="nextMediaType">The next media type that will play.</param>
  301. /// <param name="positionTicks">Optional. The position, in ticks, where playback stopped. 1 tick = 10000 ms.</param>
  302. /// <param name="liveStreamId">The live stream id.</param>
  303. /// <param name="playSessionId">The play session id.</param>
  304. /// <response code="204">Playback stop recorded.</response>
  305. /// <returns>A <see cref="NoContentResult"/>.</returns>
  306. [HttpDelete("Users/{userId}/PlayingItems/{itemId}")]
  307. [ProducesResponseType(StatusCodes.Status204NoContent)]
  308. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
  309. public async Task<ActionResult> OnPlaybackStopped(
  310. [FromRoute, Required] Guid userId,
  311. [FromRoute, Required] Guid itemId,
  312. [FromQuery] string? mediaSourceId,
  313. [FromQuery] string? nextMediaType,
  314. [FromQuery] long? positionTicks,
  315. [FromQuery] string? liveStreamId,
  316. [FromQuery] string? playSessionId)
  317. {
  318. var playbackStopInfo = new PlaybackStopInfo
  319. {
  320. ItemId = itemId,
  321. PositionTicks = positionTicks,
  322. MediaSourceId = mediaSourceId,
  323. PlaySessionId = playSessionId,
  324. LiveStreamId = liveStreamId,
  325. NextMediaType = nextMediaType
  326. };
  327. _logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", playbackStopInfo.PlaySessionId ?? string.Empty);
  328. if (!string.IsNullOrWhiteSpace(playbackStopInfo.PlaySessionId))
  329. {
  330. await _transcodingJobHelper.KillTranscodingJobs(User.GetDeviceId()!, playbackStopInfo.PlaySessionId, s => true).ConfigureAwait(false);
  331. }
  332. playbackStopInfo.SessionId = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  333. await _sessionManager.OnPlaybackStopped(playbackStopInfo).ConfigureAwait(false);
  334. return NoContent();
  335. }
  336. /// <summary>
  337. /// Updates the played status.
  338. /// </summary>
  339. /// <param name="user">The user.</param>
  340. /// <param name="item">The item.</param>
  341. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  342. /// <param name="datePlayed">The date played.</param>
  343. /// <returns>Task.</returns>
  344. private UserItemDataDto UpdatePlayedStatus(User user, BaseItem item, bool wasPlayed, DateTime? datePlayed)
  345. {
  346. if (wasPlayed)
  347. {
  348. item.MarkPlayed(user, datePlayed, true);
  349. }
  350. else
  351. {
  352. item.MarkUnplayed(user);
  353. }
  354. return _userDataRepository.GetUserDataDto(item, user);
  355. }
  356. private PlayMethod ValidatePlayMethod(PlayMethod method, string? playSessionId)
  357. {
  358. if (method == PlayMethod.Transcode)
  359. {
  360. var job = string.IsNullOrWhiteSpace(playSessionId) ? null : _transcodingJobHelper.GetTranscodingJob(playSessionId);
  361. if (job is null)
  362. {
  363. return PlayMethod.DirectPlay;
  364. }
  365. }
  366. return method;
  367. }
  368. }