SessionController.cs 18 KB

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