SessionController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Api.Extensions;
  7. using Jellyfin.Api.Helpers;
  8. using Jellyfin.Api.ModelBinders;
  9. using Jellyfin.Data.Enums;
  10. using MediaBrowser.Common.Api;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.Session;
  13. using MediaBrowser.Model.Dto;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.Session;
  16. using Microsoft.AspNetCore.Authorization;
  17. using Microsoft.AspNetCore.Http;
  18. using Microsoft.AspNetCore.Mvc;
  19. namespace Jellyfin.Api.Controllers;
  20. /// <summary>
  21. /// The session controller.
  22. /// </summary>
  23. [Route("")]
  24. public class SessionController : BaseJellyfinApiController
  25. {
  26. private readonly ISessionManager _sessionManager;
  27. private readonly IUserManager _userManager;
  28. /// <summary>
  29. /// Initializes a new instance of the <see cref="SessionController"/> class.
  30. /// </summary>
  31. /// <param name="sessionManager">Instance of <see cref="ISessionManager"/> interface.</param>
  32. /// <param name="userManager">Instance of <see cref="IUserManager"/> interface.</param>
  33. public SessionController(
  34. ISessionManager sessionManager,
  35. IUserManager userManager)
  36. {
  37. _sessionManager = sessionManager;
  38. _userManager = userManager;
  39. }
  40. /// <summary>
  41. /// Gets a list of sessions.
  42. /// </summary>
  43. /// <param name="controllableByUserId">Filter by sessions that a given user is allowed to remote control.</param>
  44. /// <param name="deviceId">Filter by device Id.</param>
  45. /// <param name="activeWithinSeconds">Optional. Filter by sessions that were active in the last n seconds.</param>
  46. /// <response code="200">List of sessions returned.</response>
  47. /// <returns>An <see cref="IReadOnlyList{SessionInfoDto}"/> with the available sessions.</returns>
  48. [HttpGet("Sessions")]
  49. [Authorize]
  50. [ProducesResponseType(StatusCodes.Status200OK)]
  51. public ActionResult<IReadOnlyList<SessionInfoDto>> GetSessions(
  52. [FromQuery] Guid? controllableByUserId,
  53. [FromQuery] string? deviceId,
  54. [FromQuery] int? activeWithinSeconds)
  55. {
  56. Guid? controllableUserToCheck = controllableByUserId is null ? null : RequestHelpers.GetUserId(User, controllableByUserId);
  57. var result = _sessionManager.GetSessions(
  58. User.GetUserId(),
  59. deviceId,
  60. activeWithinSeconds,
  61. controllableUserToCheck);
  62. return Ok(result);
  63. }
  64. /// <summary>
  65. /// Instructs a session to browse to an item or view.
  66. /// </summary>
  67. /// <param name="sessionId">The session Id.</param>
  68. /// <param name="itemType">The type of item to browse to.</param>
  69. /// <param name="itemId">The Id of the item.</param>
  70. /// <param name="itemName">The name of the item.</param>
  71. /// <response code="204">Instruction sent to session.</response>
  72. /// <returns>A <see cref="NoContentResult"/>.</returns>
  73. [HttpPost("Sessions/{sessionId}/Viewing")]
  74. [Authorize]
  75. [ProducesResponseType(StatusCodes.Status204NoContent)]
  76. public async Task<ActionResult> DisplayContent(
  77. [FromRoute, Required] string sessionId,
  78. [FromQuery, Required] BaseItemKind itemType,
  79. [FromQuery, Required] string itemId,
  80. [FromQuery, Required] string itemName)
  81. {
  82. var command = new BrowseRequest
  83. {
  84. ItemId = itemId,
  85. ItemName = itemName,
  86. ItemType = itemType
  87. };
  88. await _sessionManager.SendBrowseCommand(
  89. await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false),
  90. sessionId,
  91. command,
  92. CancellationToken.None)
  93. .ConfigureAwait(false);
  94. return NoContent();
  95. }
  96. /// <summary>
  97. /// Instructs a session to play an item.
  98. /// </summary>
  99. /// <param name="sessionId">The session id.</param>
  100. /// <param name="playCommand">The type of play command to issue (PlayNow, PlayNext, PlayLast). Clients who have not yet implemented play next and play last may play now.</param>
  101. /// <param name="itemIds">The ids of the items to play, comma delimited.</param>
  102. /// <param name="startPositionTicks">The starting position of the first item.</param>
  103. /// <param name="mediaSourceId">Optional. The media source id.</param>
  104. /// <param name="audioStreamIndex">Optional. The index of the audio stream to play.</param>
  105. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to play.</param>
  106. /// <param name="startIndex">Optional. The start index.</param>
  107. /// <response code="204">Instruction sent to session.</response>
  108. /// <returns>A <see cref="NoContentResult"/>.</returns>
  109. [HttpPost("Sessions/{sessionId}/Playing")]
  110. [Authorize]
  111. [ProducesResponseType(StatusCodes.Status204NoContent)]
  112. public async Task<ActionResult> Play(
  113. [FromRoute, Required] string sessionId,
  114. [FromQuery, Required] PlayCommand playCommand,
  115. [FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] itemIds,
  116. [FromQuery] long? startPositionTicks,
  117. [FromQuery] string? mediaSourceId,
  118. [FromQuery] int? audioStreamIndex,
  119. [FromQuery] int? subtitleStreamIndex,
  120. [FromQuery] int? startIndex)
  121. {
  122. var playRequest = new PlayRequest
  123. {
  124. ItemIds = itemIds,
  125. StartPositionTicks = startPositionTicks,
  126. PlayCommand = playCommand,
  127. MediaSourceId = mediaSourceId,
  128. AudioStreamIndex = audioStreamIndex,
  129. SubtitleStreamIndex = subtitleStreamIndex,
  130. StartIndex = startIndex
  131. };
  132. await _sessionManager.SendPlayCommand(
  133. await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false),
  134. sessionId,
  135. playRequest,
  136. CancellationToken.None)
  137. .ConfigureAwait(false);
  138. return NoContent();
  139. }
  140. /// <summary>
  141. /// Issues a playstate command to a client.
  142. /// </summary>
  143. /// <param name="sessionId">The session id.</param>
  144. /// <param name="command">The <see cref="PlaystateCommand"/>.</param>
  145. /// <param name="seekPositionTicks">The optional position ticks.</param>
  146. /// <param name="controllingUserId">The optional controlling user id.</param>
  147. /// <response code="204">Playstate command sent to session.</response>
  148. /// <returns>A <see cref="NoContentResult"/>.</returns>
  149. [HttpPost("Sessions/{sessionId}/Playing/{command}")]
  150. [Authorize]
  151. [ProducesResponseType(StatusCodes.Status204NoContent)]
  152. public async Task<ActionResult> SendPlaystateCommand(
  153. [FromRoute, Required] string sessionId,
  154. [FromRoute, Required] PlaystateCommand command,
  155. [FromQuery] long? seekPositionTicks,
  156. [FromQuery] string? controllingUserId)
  157. {
  158. await _sessionManager.SendPlaystateCommand(
  159. await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false),
  160. sessionId,
  161. new PlaystateRequest()
  162. {
  163. Command = command,
  164. ControllingUserId = controllingUserId,
  165. SeekPositionTicks = seekPositionTicks,
  166. },
  167. CancellationToken.None)
  168. .ConfigureAwait(false);
  169. return NoContent();
  170. }
  171. /// <summary>
  172. /// Issues a system command to a client.
  173. /// </summary>
  174. /// <param name="sessionId">The session id.</param>
  175. /// <param name="command">The command to send.</param>
  176. /// <response code="204">System command sent to session.</response>
  177. /// <returns>A <see cref="NoContentResult"/>.</returns>
  178. [HttpPost("Sessions/{sessionId}/System/{command}")]
  179. [Authorize]
  180. [ProducesResponseType(StatusCodes.Status204NoContent)]
  181. public async Task<ActionResult> SendSystemCommand(
  182. [FromRoute, Required] string sessionId,
  183. [FromRoute, Required] GeneralCommandType command)
  184. {
  185. var currentSession = await RequestHelpers.GetSession(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  186. var generalCommand = new GeneralCommand
  187. {
  188. Name = command,
  189. ControllingUserId = currentSession.UserId
  190. };
  191. await _sessionManager.SendGeneralCommand(currentSession.Id, sessionId, generalCommand, CancellationToken.None).ConfigureAwait(false);
  192. return NoContent();
  193. }
  194. /// <summary>
  195. /// Issues a general command to a client.
  196. /// </summary>
  197. /// <param name="sessionId">The session id.</param>
  198. /// <param name="command">The command to send.</param>
  199. /// <response code="204">General command sent to session.</response>
  200. /// <returns>A <see cref="NoContentResult"/>.</returns>
  201. [HttpPost("Sessions/{sessionId}/Command/{command}")]
  202. [Authorize]
  203. [ProducesResponseType(StatusCodes.Status204NoContent)]
  204. public async Task<ActionResult> SendGeneralCommand(
  205. [FromRoute, Required] string sessionId,
  206. [FromRoute, Required] GeneralCommandType command)
  207. {
  208. var currentSession = await RequestHelpers.GetSession(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  209. var generalCommand = new GeneralCommand
  210. {
  211. Name = command,
  212. ControllingUserId = currentSession.UserId
  213. };
  214. await _sessionManager.SendGeneralCommand(currentSession.Id, sessionId, generalCommand, CancellationToken.None)
  215. .ConfigureAwait(false);
  216. return NoContent();
  217. }
  218. /// <summary>
  219. /// Issues a full general command to a client.
  220. /// </summary>
  221. /// <param name="sessionId">The session id.</param>
  222. /// <param name="command">The <see cref="GeneralCommand"/>.</param>
  223. /// <response code="204">Full general command sent to session.</response>
  224. /// <returns>A <see cref="NoContentResult"/>.</returns>
  225. [HttpPost("Sessions/{sessionId}/Command")]
  226. [Authorize]
  227. [ProducesResponseType(StatusCodes.Status204NoContent)]
  228. public async Task<ActionResult> SendFullGeneralCommand(
  229. [FromRoute, Required] string sessionId,
  230. [FromBody, Required] GeneralCommand command)
  231. {
  232. var currentSession = await RequestHelpers.GetSession(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  233. ArgumentNullException.ThrowIfNull(command);
  234. command.ControllingUserId = currentSession.UserId;
  235. await _sessionManager.SendGeneralCommand(
  236. currentSession.Id,
  237. sessionId,
  238. command,
  239. CancellationToken.None)
  240. .ConfigureAwait(false);
  241. return NoContent();
  242. }
  243. /// <summary>
  244. /// Issues a command to a client to display a message to the user.
  245. /// </summary>
  246. /// <param name="sessionId">The session id.</param>
  247. /// <param name="command">The <see cref="MessageCommand" /> object containing Header, Message Text, and TimeoutMs.</param>
  248. /// <response code="204">Message sent.</response>
  249. /// <returns>A <see cref="NoContentResult"/>.</returns>
  250. [HttpPost("Sessions/{sessionId}/Message")]
  251. [Authorize]
  252. [ProducesResponseType(StatusCodes.Status204NoContent)]
  253. public async Task<ActionResult> SendMessageCommand(
  254. [FromRoute, Required] string sessionId,
  255. [FromBody, Required] MessageCommand command)
  256. {
  257. if (string.IsNullOrWhiteSpace(command.Header))
  258. {
  259. command.Header = "Message from Server";
  260. }
  261. await _sessionManager.SendMessageCommand(
  262. await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false),
  263. sessionId,
  264. command,
  265. CancellationToken.None)
  266. .ConfigureAwait(false);
  267. return NoContent();
  268. }
  269. /// <summary>
  270. /// Adds an additional user to a session.
  271. /// </summary>
  272. /// <param name="sessionId">The session id.</param>
  273. /// <param name="userId">The user id.</param>
  274. /// <response code="204">User added to session.</response>
  275. /// <returns>A <see cref="NoContentResult"/>.</returns>
  276. [HttpPost("Sessions/{sessionId}/User/{userId}")]
  277. [Authorize]
  278. [ProducesResponseType(StatusCodes.Status204NoContent)]
  279. public ActionResult AddUserToSession(
  280. [FromRoute, Required] string sessionId,
  281. [FromRoute, Required] Guid userId)
  282. {
  283. _sessionManager.AddAdditionalUser(sessionId, userId);
  284. return NoContent();
  285. }
  286. /// <summary>
  287. /// Removes an additional user from a session.
  288. /// </summary>
  289. /// <param name="sessionId">The session id.</param>
  290. /// <param name="userId">The user id.</param>
  291. /// <response code="204">User removed from session.</response>
  292. /// <returns>A <see cref="NoContentResult"/>.</returns>
  293. [HttpDelete("Sessions/{sessionId}/User/{userId}")]
  294. [Authorize]
  295. [ProducesResponseType(StatusCodes.Status204NoContent)]
  296. public ActionResult RemoveUserFromSession(
  297. [FromRoute, Required] string sessionId,
  298. [FromRoute, Required] Guid userId)
  299. {
  300. _sessionManager.RemoveAdditionalUser(sessionId, userId);
  301. return NoContent();
  302. }
  303. /// <summary>
  304. /// Updates capabilities for a device.
  305. /// </summary>
  306. /// <param name="id">The session id.</param>
  307. /// <param name="playableMediaTypes">A list of playable media types, comma delimited. Audio, Video, Book, Photo.</param>
  308. /// <param name="supportedCommands">A list of supported remote control commands, comma delimited.</param>
  309. /// <param name="supportsMediaControl">Determines whether media can be played remotely..</param>
  310. /// <param name="supportsPersistentIdentifier">Determines whether the device supports a unique identifier.</param>
  311. /// <response code="204">Capabilities posted.</response>
  312. /// <returns>A <see cref="NoContentResult"/>.</returns>
  313. [HttpPost("Sessions/Capabilities")]
  314. [Authorize]
  315. [ProducesResponseType(StatusCodes.Status204NoContent)]
  316. public async Task<ActionResult> PostCapabilities(
  317. [FromQuery] string? id,
  318. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] MediaType[] playableMediaTypes,
  319. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] GeneralCommandType[] supportedCommands,
  320. [FromQuery] bool supportsMediaControl = false,
  321. [FromQuery] bool supportsPersistentIdentifier = true)
  322. {
  323. if (string.IsNullOrWhiteSpace(id))
  324. {
  325. id = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  326. }
  327. _sessionManager.ReportCapabilities(id, new ClientCapabilities
  328. {
  329. PlayableMediaTypes = playableMediaTypes,
  330. SupportedCommands = supportedCommands,
  331. SupportsMediaControl = supportsMediaControl,
  332. SupportsPersistentIdentifier = supportsPersistentIdentifier
  333. });
  334. return NoContent();
  335. }
  336. /// <summary>
  337. /// Updates capabilities for a device.
  338. /// </summary>
  339. /// <param name="id">The session id.</param>
  340. /// <param name="capabilities">The <see cref="ClientCapabilities"/>.</param>
  341. /// <response code="204">Capabilities updated.</response>
  342. /// <returns>A <see cref="NoContentResult"/>.</returns>
  343. [HttpPost("Sessions/Capabilities/Full")]
  344. [Authorize]
  345. [ProducesResponseType(StatusCodes.Status204NoContent)]
  346. public async Task<ActionResult> PostFullCapabilities(
  347. [FromQuery] string? id,
  348. [FromBody, Required] ClientCapabilitiesDto capabilities)
  349. {
  350. if (string.IsNullOrWhiteSpace(id))
  351. {
  352. id = await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  353. }
  354. _sessionManager.ReportCapabilities(id, capabilities.ToClientCapabilities());
  355. return NoContent();
  356. }
  357. /// <summary>
  358. /// Reports that a session is viewing an item.
  359. /// </summary>
  360. /// <param name="sessionId">The session id.</param>
  361. /// <param name="itemId">The item id.</param>
  362. /// <response code="204">Session reported to server.</response>
  363. /// <returns>A <see cref="NoContentResult"/>.</returns>
  364. [HttpPost("Sessions/Viewing")]
  365. [Authorize]
  366. [ProducesResponseType(StatusCodes.Status204NoContent)]
  367. public async Task<ActionResult> ReportViewing(
  368. [FromQuery] string? sessionId,
  369. [FromQuery, Required] string? itemId)
  370. {
  371. string session = sessionId ?? await RequestHelpers.GetSessionId(_sessionManager, _userManager, HttpContext).ConfigureAwait(false);
  372. _sessionManager.ReportNowViewingItem(session, itemId);
  373. return NoContent();
  374. }
  375. /// <summary>
  376. /// Reports that a session has ended.
  377. /// </summary>
  378. /// <response code="204">Session end reported to server.</response>
  379. /// <returns>A <see cref="NoContentResult"/>.</returns>
  380. [HttpPost("Sessions/Logout")]
  381. [Authorize]
  382. [ProducesResponseType(StatusCodes.Status204NoContent)]
  383. public async Task<ActionResult> ReportSessionEnded()
  384. {
  385. await _sessionManager.Logout(User.GetToken()).ConfigureAwait(false);
  386. return NoContent();
  387. }
  388. /// <summary>
  389. /// Get all auth providers.
  390. /// </summary>
  391. /// <response code="200">Auth providers retrieved.</response>
  392. /// <returns>An <see cref="IEnumerable{NameIdPair}"/> with the auth providers.</returns>
  393. [HttpGet("Auth/Providers")]
  394. [Authorize(Policy = Policies.RequiresElevation)]
  395. [ProducesResponseType(StatusCodes.Status200OK)]
  396. public ActionResult<IEnumerable<NameIdPair>> GetAuthProviders()
  397. {
  398. return _userManager.GetAuthenticationProviders();
  399. }
  400. /// <summary>
  401. /// Get all password reset providers.
  402. /// </summary>
  403. /// <response code="200">Password reset providers retrieved.</response>
  404. /// <returns>An <see cref="IEnumerable{NameIdPair}"/> with the password reset providers.</returns>
  405. [HttpGet("Auth/PasswordResetProviders")]
  406. [ProducesResponseType(StatusCodes.Status200OK)]
  407. [Authorize(Policy = Policies.RequiresElevation)]
  408. public ActionResult<IEnumerable<NameIdPair>> GetPasswordResetProviders()
  409. {
  410. return _userManager.GetPasswordResetProviders();
  411. }
  412. }