SessionsService.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. using MediaBrowser.Controller.Library;
  2. using MediaBrowser.Controller.Net;
  3. using MediaBrowser.Controller.Security;
  4. using MediaBrowser.Controller.Session;
  5. using MediaBrowser.Model.Session;
  6. using ServiceStack;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace MediaBrowser.Api.Session
  13. {
  14. /// <summary>
  15. /// Class GetSessions
  16. /// </summary>
  17. [Route("/Sessions", "GET", Summary = "Gets a list of sessions")]
  18. [Authenticated]
  19. public class GetSessions : IReturn<List<SessionInfoDto>>
  20. {
  21. [ApiMember(Name = "ControllableByUserId", Description = "Optional. Filter by sessions that a given user is allowed to remote control.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  22. public Guid? ControllableByUserId { get; set; }
  23. [ApiMember(Name = "DeviceId", Description = "Optional. Filter by device id.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  24. public string DeviceId { get; set; }
  25. }
  26. /// <summary>
  27. /// Class DisplayContent
  28. /// </summary>
  29. [Route("/Sessions/{Id}/Viewing", "POST", Summary = "Instructs a session to browse to an item or view")]
  30. [Authenticated]
  31. public class DisplayContent : IReturnVoid
  32. {
  33. /// <summary>
  34. /// Gets or sets the id.
  35. /// </summary>
  36. /// <value>The id.</value>
  37. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  38. public string Id { get; set; }
  39. /// <summary>
  40. /// Artist, Genre, Studio, Person, or any kind of BaseItem
  41. /// </summary>
  42. /// <value>The type of the item.</value>
  43. [ApiMember(Name = "ItemType", Description = "The type of item to browse to.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  44. public string ItemType { get; set; }
  45. /// <summary>
  46. /// Artist name, genre name, item Id, etc
  47. /// </summary>
  48. /// <value>The item identifier.</value>
  49. [ApiMember(Name = "ItemId", Description = "The Id of the item.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  50. public string ItemId { get; set; }
  51. /// <summary>
  52. /// Gets or sets the name of the item.
  53. /// </summary>
  54. /// <value>The name of the item.</value>
  55. [ApiMember(Name = "ItemName", Description = "The name of the item.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  56. public string ItemName { get; set; }
  57. }
  58. [Route("/Sessions/{Id}/Playing", "POST", Summary = "Instructs a session to play an item")]
  59. [Authenticated]
  60. public class Play : IReturnVoid
  61. {
  62. /// <summary>
  63. /// Gets or sets the id.
  64. /// </summary>
  65. /// <value>The id.</value>
  66. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  67. public string Id { get; set; }
  68. /// <summary>
  69. /// Artist, Genre, Studio, Person, or any kind of BaseItem
  70. /// </summary>
  71. /// <value>The type of the item.</value>
  72. [ApiMember(Name = "ItemIds", Description = "The ids of the items to play, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
  73. public string ItemIds { get; set; }
  74. /// <summary>
  75. /// Gets or sets the start position ticks that the first item should be played at
  76. /// </summary>
  77. /// <value>The start position ticks.</value>
  78. [ApiMember(Name = "StartPositionTicks", Description = "The starting position of the first item.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
  79. public long? StartPositionTicks { get; set; }
  80. /// <summary>
  81. /// Gets or sets the play command.
  82. /// </summary>
  83. /// <value>The play command.</value>
  84. [ApiMember(Name = "PlayCommand", Description = "The type of play command to issue (PlayNow, PlayNext, PlayLast). Clients who have not yet implemented play next and play last may play now.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  85. public PlayCommand PlayCommand { get; set; }
  86. }
  87. [Route("/Sessions/{Id}/Playing/{Command}", "POST", Summary = "Issues a playstate command to a client")]
  88. [Authenticated]
  89. public class SendPlaystateCommand : IReturnVoid
  90. {
  91. /// <summary>
  92. /// Gets or sets the id.
  93. /// </summary>
  94. /// <value>The id.</value>
  95. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  96. public string Id { get; set; }
  97. /// <summary>
  98. /// Gets or sets the position to seek to
  99. /// </summary>
  100. [ApiMember(Name = "SeekPositionTicks", Description = "The position to seek to.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
  101. public long? SeekPositionTicks { get; set; }
  102. /// <summary>
  103. /// Gets or sets the play command.
  104. /// </summary>
  105. /// <value>The play command.</value>
  106. [ApiMember(Name = "Command", Description = "The command to send - stop, pause, unpause, nexttrack, previoustrack, seek, fullscreen.", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  107. public PlaystateCommand Command { get; set; }
  108. }
  109. [Route("/Sessions/{Id}/System/{Command}", "POST", Summary = "Issues a system command to a client")]
  110. [Authenticated]
  111. public class SendSystemCommand : IReturnVoid
  112. {
  113. /// <summary>
  114. /// Gets or sets the id.
  115. /// </summary>
  116. /// <value>The id.</value>
  117. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  118. public string Id { get; set; }
  119. /// <summary>
  120. /// Gets or sets the command.
  121. /// </summary>
  122. /// <value>The play command.</value>
  123. [ApiMember(Name = "Command", Description = "The command to send.", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  124. public string Command { get; set; }
  125. }
  126. [Route("/Sessions/{Id}/Command/{Command}", "POST", Summary = "Issues a system command to a client")]
  127. [Authenticated]
  128. public class SendGeneralCommand : IReturnVoid
  129. {
  130. /// <summary>
  131. /// Gets or sets the id.
  132. /// </summary>
  133. /// <value>The id.</value>
  134. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  135. public string Id { get; set; }
  136. /// <summary>
  137. /// Gets or sets the command.
  138. /// </summary>
  139. /// <value>The play command.</value>
  140. [ApiMember(Name = "Command", Description = "The command to send.", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  141. public string Command { get; set; }
  142. }
  143. [Route("/Sessions/{Id}/Command", "POST", Summary = "Issues a system command to a client")]
  144. [Authenticated]
  145. public class SendFullGeneralCommand : GeneralCommand, IReturnVoid
  146. {
  147. /// <summary>
  148. /// Gets or sets the id.
  149. /// </summary>
  150. /// <value>The id.</value>
  151. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  152. public string Id { get; set; }
  153. }
  154. [Route("/Sessions/{Id}/Message", "POST", Summary = "Issues a command to a client to display a message to the user")]
  155. [Authenticated]
  156. public class SendMessageCommand : IReturnVoid
  157. {
  158. /// <summary>
  159. /// Gets or sets the id.
  160. /// </summary>
  161. /// <value>The id.</value>
  162. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  163. public string Id { get; set; }
  164. [ApiMember(Name = "Text", Description = "The message text.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  165. public string Text { get; set; }
  166. [ApiMember(Name = "Header", Description = "The message header.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  167. public string Header { get; set; }
  168. [ApiMember(Name = "TimeoutMs", Description = "The message timeout. If omitted the user will have to confirm viewing the message.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
  169. public long? TimeoutMs { get; set; }
  170. }
  171. [Route("/Sessions/{Id}/Users/{UserId}", "POST", Summary = "Adds an additional user to a session")]
  172. [Authenticated]
  173. public class AddUserToSession : IReturnVoid
  174. {
  175. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  176. public string Id { get; set; }
  177. [ApiMember(Name = "UserId", Description = "UserId Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  178. public Guid UserId { get; set; }
  179. }
  180. [Route("/Sessions/{Id}/Users/{UserId}", "DELETE", Summary = "Removes an additional user from a session")]
  181. [Authenticated]
  182. public class RemoveUserFromSession : IReturnVoid
  183. {
  184. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  185. public string Id { get; set; }
  186. [ApiMember(Name = "UserId", Description = "UserId Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  187. public Guid UserId { get; set; }
  188. }
  189. [Route("/Sessions/Capabilities", "POST", Summary = "Updates capabilities for a device")]
  190. [Authenticated]
  191. public class PostCapabilities : IReturnVoid
  192. {
  193. /// <summary>
  194. /// Gets or sets the id.
  195. /// </summary>
  196. /// <value>The id.</value>
  197. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  198. public string Id { get; set; }
  199. [ApiMember(Name = "PlayableMediaTypes", Description = "A list of playable media types, comma delimited. Audio, Video, Book, Game, Photo.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
  200. public string PlayableMediaTypes { get; set; }
  201. [ApiMember(Name = "SupportedCommands", Description = "A list of supported remote control commands, comma delimited", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
  202. public string SupportedCommands { get; set; }
  203. [ApiMember(Name = "MessageCallbackUrl", Description = "A url to post messages to, including remote control commands.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
  204. public string MessageCallbackUrl { get; set; }
  205. [ApiMember(Name = "SupportsMediaControl", Description = "Determines whether media can be played remotely.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "POST")]
  206. public bool SupportsMediaControl { get; set; }
  207. }
  208. [Route("/Sessions/Logout", "POST", Summary = "Reports that a session has ended")]
  209. public class ReportSessionEnded : IReturnVoid
  210. {
  211. }
  212. [Route("/Auth/Keys", "GET")]
  213. public class GetApiKeys
  214. {
  215. }
  216. [Route("/Auth/Keys/{Key}", "DELETE")]
  217. public class RevokeKey
  218. {
  219. [ApiMember(Name = "Key", Description = "Auth Key", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  220. public string Key { get; set; }
  221. }
  222. [Route("/Auth/Keys", "POST")]
  223. public class CreateKey
  224. {
  225. [ApiMember(Name = "App", Description = "App", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  226. public string App { get; set; }
  227. }
  228. /// <summary>
  229. /// Class SessionsService
  230. /// </summary>
  231. public class SessionsService : BaseApiService
  232. {
  233. /// <summary>
  234. /// The _session manager
  235. /// </summary>
  236. private readonly ISessionManager _sessionManager;
  237. private readonly IUserManager _userManager;
  238. private readonly IAuthorizationContext _authContext;
  239. private readonly IAuthenticationRepository _authRepo;
  240. /// <summary>
  241. /// Initializes a new instance of the <see cref="SessionsService" /> class.
  242. /// </summary>
  243. /// <param name="sessionManager">The session manager.</param>
  244. /// <param name="userManager">The user manager.</param>
  245. /// <param name="authContext">The authentication context.</param>
  246. /// <param name="authRepo">The authentication repo.</param>
  247. public SessionsService(ISessionManager sessionManager, IUserManager userManager, IAuthorizationContext authContext, IAuthenticationRepository authRepo)
  248. {
  249. _sessionManager = sessionManager;
  250. _userManager = userManager;
  251. _authContext = authContext;
  252. _authRepo = authRepo;
  253. }
  254. public void Delete(RevokeKey request)
  255. {
  256. var task = _sessionManager.RevokeToken(request.Key);
  257. Task.WaitAll(task);
  258. }
  259. public Task Post(CreateKey request)
  260. {
  261. return _authRepo.Create(new AuthenticationInfo
  262. {
  263. AppName = request.App,
  264. IsActive = true,
  265. AccessToken = Guid.NewGuid().ToString("N"),
  266. DateCreated = DateTime.UtcNow
  267. }, CancellationToken.None);
  268. }
  269. public void Post(ReportSessionEnded request)
  270. {
  271. var auth = _authContext.GetAuthorizationInfo(Request);
  272. _sessionManager.Logout(auth.Token);
  273. }
  274. public object Get(GetApiKeys request)
  275. {
  276. var result = _authRepo.Get(new AuthenticationInfoQuery
  277. {
  278. IsActive = true
  279. });
  280. return ToOptimizedResult(result);
  281. }
  282. /// <summary>
  283. /// Gets the specified request.
  284. /// </summary>
  285. /// <param name="request">The request.</param>
  286. /// <returns>System.Object.</returns>
  287. public object Get(GetSessions request)
  288. {
  289. var result = _sessionManager.Sessions.Where(i => i.IsActive);
  290. if (!string.IsNullOrEmpty(request.DeviceId))
  291. {
  292. result = result.Where(i => string.Equals(i.DeviceId, request.DeviceId, StringComparison.OrdinalIgnoreCase));
  293. }
  294. if (request.ControllableByUserId.HasValue)
  295. {
  296. result = result.Where(i => i.SupportsMediaControl);
  297. var user = _userManager.GetUserById(request.ControllableByUserId.Value);
  298. if (!user.Configuration.EnableRemoteControlOfOtherUsers)
  299. {
  300. result = result.Where(i => !i.UserId.HasValue || i.ContainsUser(request.ControllableByUserId.Value));
  301. }
  302. }
  303. return ToOptimizedResult(result.Select(_sessionManager.GetSessionInfoDto).ToList());
  304. }
  305. public Task Post(SendPlaystateCommand request)
  306. {
  307. var command = new PlaystateRequest
  308. {
  309. Command = request.Command,
  310. SeekPositionTicks = request.SeekPositionTicks
  311. };
  312. return _sessionManager.SendPlaystateCommand(GetSession().Id, request.Id, command, CancellationToken.None);
  313. }
  314. /// <summary>
  315. /// Posts the specified request.
  316. /// </summary>
  317. /// <param name="request">The request.</param>
  318. public Task Post(DisplayContent request)
  319. {
  320. var command = new BrowseRequest
  321. {
  322. ItemId = request.ItemId,
  323. ItemName = request.ItemName,
  324. ItemType = request.ItemType
  325. };
  326. return _sessionManager.SendBrowseCommand(GetSession().Id, request.Id, command, CancellationToken.None);
  327. }
  328. /// <summary>
  329. /// Posts the specified request.
  330. /// </summary>
  331. /// <param name="request">The request.</param>
  332. public Task Post(SendSystemCommand request)
  333. {
  334. GeneralCommandType commandType;
  335. var name = request.Command;
  336. if (Enum.TryParse(name, true, out commandType))
  337. {
  338. name = commandType.ToString();
  339. }
  340. var currentSession = GetSession();
  341. var command = new GeneralCommand
  342. {
  343. Name = name,
  344. ControllingUserId = currentSession.UserId.HasValue ? currentSession.UserId.Value.ToString("N") : null
  345. };
  346. return _sessionManager.SendGeneralCommand(currentSession.Id, request.Id, command, CancellationToken.None);
  347. }
  348. /// <summary>
  349. /// Posts the specified request.
  350. /// </summary>
  351. /// <param name="request">The request.</param>
  352. public Task Post(SendMessageCommand request)
  353. {
  354. var command = new MessageCommand
  355. {
  356. Header = string.IsNullOrEmpty(request.Header) ? "Message from Server" : request.Header,
  357. TimeoutMs = request.TimeoutMs,
  358. Text = request.Text
  359. };
  360. return _sessionManager.SendMessageCommand(GetSession().Id, request.Id, command, CancellationToken.None);
  361. }
  362. /// <summary>
  363. /// Posts the specified request.
  364. /// </summary>
  365. /// <param name="request">The request.</param>
  366. public Task Post(Play request)
  367. {
  368. var command = new PlayRequest
  369. {
  370. ItemIds = request.ItemIds.Split(',').ToArray(),
  371. PlayCommand = request.PlayCommand,
  372. StartPositionTicks = request.StartPositionTicks
  373. };
  374. return _sessionManager.SendPlayCommand(GetSession().Id, request.Id, command, CancellationToken.None);
  375. }
  376. public Task Post(SendGeneralCommand request)
  377. {
  378. var currentSession = GetSession();
  379. var command = new GeneralCommand
  380. {
  381. Name = request.Command,
  382. ControllingUserId = currentSession.UserId.HasValue ? currentSession.UserId.Value.ToString("N") : null
  383. };
  384. return _sessionManager.SendGeneralCommand(currentSession.Id, request.Id, command, CancellationToken.None);
  385. }
  386. public Task Post(SendFullGeneralCommand request)
  387. {
  388. var currentSession = GetSession();
  389. request.ControllingUserId = currentSession.UserId.HasValue ? currentSession.UserId.Value.ToString("N") : null;
  390. return _sessionManager.SendGeneralCommand(currentSession.Id, request.Id, request, CancellationToken.None);
  391. }
  392. public void Post(AddUserToSession request)
  393. {
  394. _sessionManager.AddAdditionalUser(request.Id, request.UserId);
  395. }
  396. public void Delete(RemoveUserFromSession request)
  397. {
  398. _sessionManager.RemoveAdditionalUser(request.Id, request.UserId);
  399. }
  400. public void Post(PostCapabilities request)
  401. {
  402. if (string.IsNullOrWhiteSpace(request.Id))
  403. {
  404. request.Id = GetSession().Id;
  405. }
  406. _sessionManager.ReportCapabilities(request.Id, new SessionCapabilities
  407. {
  408. PlayableMediaTypes = request.PlayableMediaTypes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(),
  409. SupportedCommands = request.SupportedCommands.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(),
  410. SupportsMediaControl = request.SupportsMediaControl,
  411. MessageCallbackUrl = request.MessageCallbackUrl
  412. });
  413. }
  414. }
  415. }