SessionsService.cs 19 KB

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