SessionsService.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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
  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 void Post(CreateKey request)
  260. {
  261. var task = _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. Task.WaitAll(task);
  269. }
  270. public void Post(ReportSessionEnded request)
  271. {
  272. var auth = _authContext.GetAuthorizationInfo(Request);
  273. _sessionManager.Logout(auth.Token);
  274. }
  275. public object Get(GetApiKeys request)
  276. {
  277. var result = _authRepo.Get(new AuthenticationInfoQuery
  278. {
  279. IsActive = true
  280. });
  281. return ToOptimizedResult(result);
  282. }
  283. /// <summary>
  284. /// Gets the specified request.
  285. /// </summary>
  286. /// <param name="request">The request.</param>
  287. /// <returns>System.Object.</returns>
  288. public object Get(GetSessions request)
  289. {
  290. var result = _sessionManager.Sessions.Where(i => i.IsActive);
  291. if (!string.IsNullOrEmpty(request.DeviceId))
  292. {
  293. result = result.Where(i => string.Equals(i.DeviceId, request.DeviceId, StringComparison.OrdinalIgnoreCase));
  294. }
  295. if (request.ControllableByUserId.HasValue)
  296. {
  297. result = result.Where(i => i.SupportsMediaControl);
  298. var user = _userManager.GetUserById(request.ControllableByUserId.Value);
  299. if (!user.Configuration.EnableRemoteControlOfOtherUsers)
  300. {
  301. result = result.Where(i => !i.UserId.HasValue || i.ContainsUser(request.ControllableByUserId.Value));
  302. }
  303. }
  304. return ToOptimizedResult(result.Select(_sessionManager.GetSessionInfoDto).ToList());
  305. }
  306. public void Post(SendPlaystateCommand request)
  307. {
  308. var command = new PlaystateRequest
  309. {
  310. Command = request.Command,
  311. SeekPositionTicks = request.SeekPositionTicks
  312. };
  313. var task = _sessionManager.SendPlaystateCommand(GetSession().Id, request.Id, command, CancellationToken.None);
  314. Task.WaitAll(task);
  315. }
  316. /// <summary>
  317. /// Posts the specified request.
  318. /// </summary>
  319. /// <param name="request">The request.</param>
  320. public void Post(DisplayContent request)
  321. {
  322. var command = new BrowseRequest
  323. {
  324. ItemId = request.ItemId,
  325. ItemName = request.ItemName,
  326. ItemType = request.ItemType
  327. };
  328. var task = _sessionManager.SendBrowseCommand(GetSession().Id, request.Id, command, CancellationToken.None);
  329. Task.WaitAll(task);
  330. }
  331. /// <summary>
  332. /// Posts the specified request.
  333. /// </summary>
  334. /// <param name="request">The request.</param>
  335. public void Post(SendSystemCommand request)
  336. {
  337. GeneralCommandType commandType;
  338. if (Enum.TryParse(request.Command, true, out commandType))
  339. {
  340. var currentSession = GetSession();
  341. var command = new GeneralCommand
  342. {
  343. Name = commandType.ToString(),
  344. ControllingUserId = currentSession.UserId.HasValue ? currentSession.UserId.Value.ToString("N") : null
  345. };
  346. var task = _sessionManager.SendGeneralCommand(currentSession.Id, request.Id, command, CancellationToken.None);
  347. Task.WaitAll(task);
  348. }
  349. }
  350. /// <summary>
  351. /// Posts the specified request.
  352. /// </summary>
  353. /// <param name="request">The request.</param>
  354. public void Post(SendMessageCommand request)
  355. {
  356. var command = new MessageCommand
  357. {
  358. Header = string.IsNullOrEmpty(request.Header) ? "Message from Server" : request.Header,
  359. TimeoutMs = request.TimeoutMs,
  360. Text = request.Text
  361. };
  362. var task = _sessionManager.SendMessageCommand(GetSession().Id, request.Id, command, CancellationToken.None);
  363. Task.WaitAll(task);
  364. }
  365. /// <summary>
  366. /// Posts the specified request.
  367. /// </summary>
  368. /// <param name="request">The request.</param>
  369. public void Post(Play request)
  370. {
  371. var command = new PlayRequest
  372. {
  373. ItemIds = request.ItemIds.Split(',').ToArray(),
  374. PlayCommand = request.PlayCommand,
  375. StartPositionTicks = request.StartPositionTicks
  376. };
  377. var task = _sessionManager.SendPlayCommand(GetSession().Id, request.Id, command, CancellationToken.None);
  378. Task.WaitAll(task);
  379. }
  380. public void Post(SendGeneralCommand request)
  381. {
  382. var currentSession = GetSession();
  383. var command = new GeneralCommand
  384. {
  385. Name = request.Command,
  386. ControllingUserId = currentSession.UserId.HasValue ? currentSession.UserId.Value.ToString("N") : null
  387. };
  388. var task = _sessionManager.SendGeneralCommand(currentSession.Id, request.Id, command, CancellationToken.None);
  389. Task.WaitAll(task);
  390. }
  391. public void Post(SendFullGeneralCommand request)
  392. {
  393. var currentSession = GetSession();
  394. request.ControllingUserId = currentSession.UserId.HasValue ? currentSession.UserId.Value.ToString("N") : null;
  395. var task = _sessionManager.SendGeneralCommand(currentSession.Id, request.Id, request, CancellationToken.None);
  396. Task.WaitAll(task);
  397. }
  398. public void Post(AddUserToSession request)
  399. {
  400. _sessionManager.AddAdditionalUser(request.Id, request.UserId);
  401. }
  402. public void Delete(RemoveUserFromSession request)
  403. {
  404. _sessionManager.RemoveAdditionalUser(request.Id, request.UserId);
  405. }
  406. public void Post(PostCapabilities request)
  407. {
  408. if (string.IsNullOrWhiteSpace(request.Id))
  409. {
  410. request.Id = GetSession().Id;
  411. }
  412. _sessionManager.ReportCapabilities(request.Id, new SessionCapabilities
  413. {
  414. PlayableMediaTypes = request.PlayableMediaTypes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(),
  415. SupportedCommands = request.SupportedCommands.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(),
  416. SupportsMediaControl = request.SupportsMediaControl,
  417. MessageCallbackUrl = request.MessageCallbackUrl
  418. });
  419. }
  420. }
  421. }