SessionController.cs 18 KB

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