SessionsService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Dto;
  3. using MediaBrowser.Controller.Session;
  4. using MediaBrowser.Model.Net;
  5. using MediaBrowser.Model.Session;
  6. using ServiceStack.ServiceHost;
  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")]
  18. [Api(("Gets a list of sessions"))]
  19. public class GetSessions : IReturn<List<SessionInfoDto>>
  20. {
  21. /// <summary>
  22. /// Gets or sets a value indicating whether [supports remote control].
  23. /// </summary>
  24. /// <value><c>null</c> if [supports remote control] contains no value, <c>true</c> if [supports remote control]; otherwise, <c>false</c>.</value>
  25. [ApiMember(Name = "SupportsRemoteControl", Description = "Optional. Filter by sessions that can be remote controlled.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
  26. public bool? SupportsRemoteControl { get; set; }
  27. [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")]
  28. public Guid? ControllableByUserId { get; set; }
  29. }
  30. /// <summary>
  31. /// Class BrowseTo
  32. /// </summary>
  33. [Route("/Sessions/{Id}/Viewing", "POST")]
  34. [Api(("Instructs a session to browse to an item or view"))]
  35. public class BrowseTo : IReturnVoid
  36. {
  37. /// <summary>
  38. /// Gets or sets the id.
  39. /// </summary>
  40. /// <value>The id.</value>
  41. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  42. public Guid Id { get; set; }
  43. /// <summary>
  44. /// Artist, Genre, Studio, Person, or any kind of BaseItem
  45. /// </summary>
  46. /// <value>The type of the item.</value>
  47. [ApiMember(Name = "ItemType", Description = "The type of item to browse to.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  48. public string ItemType { get; set; }
  49. /// <summary>
  50. /// Artist name, genre name, item Id, etc
  51. /// </summary>
  52. /// <value>The item identifier.</value>
  53. [ApiMember(Name = "ItemId", Description = "The Id of the item.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  54. public string ItemId { get; set; }
  55. /// <summary>
  56. /// Gets or sets the name of the item.
  57. /// </summary>
  58. /// <value>The name of the item.</value>
  59. [ApiMember(Name = "ItemName", Description = "The name of the item.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  60. public string ItemName { get; set; }
  61. /// <summary>
  62. /// Gets or sets the context (Movies, Music, TvShows, etc)
  63. /// Applicable to genres, studios and persons only because the context of items and artists can be inferred.
  64. /// This is optional to supply and clients are free to ignore it.
  65. /// </summary>
  66. /// <value>The context.</value>
  67. [ApiMember(Name = "Context", Description = "The ui context for the client (movies, music, tv, games etc). This is optional to supply and clients are free to ignore it.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
  68. public string Context { get; set; }
  69. }
  70. [Route("/Sessions/{Id}/Playing", "POST")]
  71. [Api(("Instructs a session to play an item"))]
  72. public class Play : IReturnVoid
  73. {
  74. /// <summary>
  75. /// Gets or sets the id.
  76. /// </summary>
  77. /// <value>The id.</value>
  78. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  79. public Guid Id { get; set; }
  80. /// <summary>
  81. /// Artist, Genre, Studio, Person, or any kind of BaseItem
  82. /// </summary>
  83. /// <value>The type of the item.</value>
  84. [ApiMember(Name = "ItemIds", Description = "The ids of the items to play, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
  85. public string ItemIds { get; set; }
  86. /// <summary>
  87. /// Gets or sets the start position ticks that the first item should be played at
  88. /// </summary>
  89. /// <value>The start position ticks.</value>
  90. [ApiMember(Name = "StartPositionTicks", Description = "The starting position of the first item.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
  91. public long? StartPositionTicks { get; set; }
  92. /// <summary>
  93. /// Gets or sets the play command.
  94. /// </summary>
  95. /// <value>The play command.</value>
  96. [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")]
  97. public PlayCommand PlayCommand { get; set; }
  98. }
  99. [Route("/Sessions/{Id}/Playing/{Command}", "POST")]
  100. [Api(("Issues a playstate command to a client"))]
  101. public class SendPlaystateCommand : IReturnVoid
  102. {
  103. /// <summary>
  104. /// Gets or sets the id.
  105. /// </summary>
  106. /// <value>The id.</value>
  107. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  108. public Guid Id { get; set; }
  109. /// <summary>
  110. /// Gets or sets the position to seek to
  111. /// </summary>
  112. [ApiMember(Name = "SeekPositionTicks", Description = "The position to seek to.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
  113. public long? SeekPositionTicks { get; set; }
  114. /// <summary>
  115. /// Gets or sets the play command.
  116. /// </summary>
  117. /// <value>The play command.</value>
  118. [ApiMember(Name = "Command", Description = "The command to send - stop, pause, unpause, nexttrack, previoustrack, seek.", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  119. public PlaystateCommand Command { get; set; }
  120. }
  121. [Route("/Sessions/{Id}/System/{Command}", "POST")]
  122. [Api(("Issues a system command to a client"))]
  123. public class SendSystemCommand : IReturnVoid
  124. {
  125. /// <summary>
  126. /// Gets or sets the id.
  127. /// </summary>
  128. /// <value>The id.</value>
  129. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  130. public Guid Id { get; set; }
  131. /// <summary>
  132. /// Gets or sets the command.
  133. /// </summary>
  134. /// <value>The play command.</value>
  135. [ApiMember(Name = "Command", Description = "The command to send.", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  136. public SystemCommand Command { get; set; }
  137. }
  138. [Route("/Sessions/{Id}/Message", "POST")]
  139. [Api(("Issues a command to a client to display a message to the user"))]
  140. public class SendMessageCommand : IReturnVoid
  141. {
  142. /// <summary>
  143. /// Gets or sets the id.
  144. /// </summary>
  145. /// <value>The id.</value>
  146. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  147. public Guid Id { get; set; }
  148. [ApiMember(Name = "Text", Description = "The message text.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  149. public string Text { get; set; }
  150. [ApiMember(Name = "Header", Description = "The message header.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  151. public string Header { get; set; }
  152. [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")]
  153. public long? TimeoutMs { get; set; }
  154. }
  155. /// <summary>
  156. /// Class SessionsService
  157. /// </summary>
  158. public class SessionsService : BaseApiService
  159. {
  160. /// <summary>
  161. /// The _session manager
  162. /// </summary>
  163. private readonly ISessionManager _sessionManager;
  164. private readonly IDtoService _dtoService;
  165. /// <summary>
  166. /// Initializes a new instance of the <see cref="SessionsService" /> class.
  167. /// </summary>
  168. /// <param name="sessionManager">The session manager.</param>
  169. public SessionsService(ISessionManager sessionManager, IDtoService dtoService)
  170. {
  171. _sessionManager = sessionManager;
  172. _dtoService = dtoService;
  173. }
  174. /// <summary>
  175. /// Gets the specified request.
  176. /// </summary>
  177. /// <param name="request">The request.</param>
  178. /// <returns>System.Object.</returns>
  179. public object Get(GetSessions request)
  180. {
  181. var result = _sessionManager.Sessions.Where(i => i.IsActive);
  182. if (request.SupportsRemoteControl.HasValue)
  183. {
  184. result = result.Where(i => i.SupportsRemoteControl == request.SupportsRemoteControl.Value);
  185. }
  186. return ToOptimizedResult(result.Select(_dtoService.GetSessionInfoDto).ToList());
  187. }
  188. public void Post(SendPlaystateCommand request)
  189. {
  190. var task = SendPlaystateCommand(request);
  191. Task.WaitAll(task);
  192. }
  193. private async Task SendPlaystateCommand(SendPlaystateCommand request)
  194. {
  195. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  196. if (session == null)
  197. {
  198. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  199. }
  200. if (!session.SupportsRemoteControl)
  201. {
  202. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  203. }
  204. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  205. if (socket != null)
  206. {
  207. try
  208. {
  209. await socket.SendAsync(new WebSocketMessage<PlaystateRequest>
  210. {
  211. MessageType = "Playstate",
  212. Data = new PlaystateRequest
  213. {
  214. Command = request.Command,
  215. SeekPositionTicks = request.SeekPositionTicks
  216. }
  217. }, CancellationToken.None).ConfigureAwait(false);
  218. }
  219. catch (Exception ex)
  220. {
  221. Logger.ErrorException("Error sending web socket message", ex);
  222. }
  223. }
  224. else
  225. {
  226. throw new InvalidOperationException("The requested session does not have an open web socket.");
  227. }
  228. }
  229. /// <summary>
  230. /// Posts the specified request.
  231. /// </summary>
  232. /// <param name="request">The request.</param>
  233. public void Post(BrowseTo request)
  234. {
  235. var task = BrowseTo(request);
  236. Task.WaitAll(task);
  237. }
  238. /// <summary>
  239. /// Browses to.
  240. /// </summary>
  241. /// <param name="request">The request.</param>
  242. /// <returns>Task.</returns>
  243. /// <exception cref="ResourceNotFoundException"></exception>
  244. /// <exception cref="System.ArgumentException"></exception>
  245. /// <exception cref="System.InvalidOperationException">The requested session does not have an open web socket.</exception>
  246. private async Task BrowseTo(BrowseTo request)
  247. {
  248. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  249. if (session == null)
  250. {
  251. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  252. }
  253. if (!session.SupportsRemoteControl)
  254. {
  255. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  256. }
  257. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  258. if (socket != null)
  259. {
  260. try
  261. {
  262. await socket.SendAsync(new WebSocketMessage<BrowseTo>
  263. {
  264. MessageType = "Browse",
  265. Data = request
  266. }, CancellationToken.None).ConfigureAwait(false);
  267. }
  268. catch (Exception ex)
  269. {
  270. Logger.ErrorException("Error sending web socket message", ex);
  271. }
  272. }
  273. else
  274. {
  275. throw new InvalidOperationException("The requested session does not have an open web socket.");
  276. }
  277. }
  278. /// <summary>
  279. /// Posts the specified request.
  280. /// </summary>
  281. /// <param name="request">The request.</param>
  282. public void Post(SendSystemCommand request)
  283. {
  284. var task = SendSystemCommand(request);
  285. Task.WaitAll(task);
  286. }
  287. private async Task SendSystemCommand(SendSystemCommand request)
  288. {
  289. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  290. if (session == null)
  291. {
  292. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  293. }
  294. if (!session.SupportsRemoteControl)
  295. {
  296. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  297. }
  298. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  299. if (socket != null)
  300. {
  301. try
  302. {
  303. await socket.SendAsync(new WebSocketMessage<string>
  304. {
  305. MessageType = "SystemCommand",
  306. Data = request.Command.ToString()
  307. }, CancellationToken.None).ConfigureAwait(false);
  308. }
  309. catch (Exception ex)
  310. {
  311. Logger.ErrorException("Error sending web socket message", ex);
  312. }
  313. }
  314. else
  315. {
  316. throw new InvalidOperationException("The requested session does not have an open web socket.");
  317. }
  318. }
  319. /// <summary>
  320. /// Posts the specified request.
  321. /// </summary>
  322. /// <param name="request">The request.</param>
  323. public void Post(SendMessageCommand request)
  324. {
  325. var task = SendMessageCommand(request);
  326. Task.WaitAll(task);
  327. }
  328. private async Task SendMessageCommand(SendMessageCommand request)
  329. {
  330. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  331. if (session == null)
  332. {
  333. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  334. }
  335. if (!session.SupportsRemoteControl)
  336. {
  337. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  338. }
  339. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  340. if (socket != null)
  341. {
  342. try
  343. {
  344. await socket.SendAsync(new WebSocketMessage<MessageCommand>
  345. {
  346. MessageType = "MessageCommand",
  347. Data = new MessageCommand
  348. {
  349. Header = string.IsNullOrEmpty(request.Header) ? "Message from Server" : request.Header,
  350. TimeoutMs = request.TimeoutMs,
  351. Text = request.Text
  352. }
  353. }, CancellationToken.None).ConfigureAwait(false);
  354. }
  355. catch (Exception ex)
  356. {
  357. Logger.ErrorException("Error sending web socket message", ex);
  358. }
  359. }
  360. else
  361. {
  362. throw new InvalidOperationException("The requested session does not have an open web socket.");
  363. }
  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 task = Play(request);
  372. Task.WaitAll(task);
  373. }
  374. /// <summary>
  375. /// Plays the specified request.
  376. /// </summary>
  377. /// <param name="request">The request.</param>
  378. /// <returns>Task.</returns>
  379. /// <exception cref="ResourceNotFoundException"></exception>
  380. /// <exception cref="System.ArgumentException"></exception>
  381. /// <exception cref="System.InvalidOperationException">The requested session does not have an open web socket.</exception>
  382. private async Task Play(Play request)
  383. {
  384. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  385. if (session == null)
  386. {
  387. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  388. }
  389. if (!session.SupportsRemoteControl)
  390. {
  391. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  392. }
  393. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  394. if (socket != null)
  395. {
  396. try
  397. {
  398. await socket.SendAsync(new WebSocketMessage<PlayRequest>
  399. {
  400. MessageType = "Play",
  401. Data = new PlayRequest
  402. {
  403. ItemIds = request.ItemIds.Split(',').ToArray(),
  404. PlayCommand = request.PlayCommand,
  405. StartPositionTicks = request.StartPositionTicks
  406. }
  407. }, CancellationToken.None).ConfigureAwait(false);
  408. }
  409. catch (Exception ex)
  410. {
  411. Logger.ErrorException("Error sending web socket message", ex);
  412. }
  413. }
  414. else
  415. {
  416. throw new InvalidOperationException("The requested session does not have an open web socket.");
  417. }
  418. }
  419. }
  420. }