PlaystateController.cs 17 KB

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