SessionsService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 = false, 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. private readonly IDtoService _dtoService;
  163. /// <summary>
  164. /// Initializes a new instance of the <see cref="SessionsService" /> class.
  165. /// </summary>
  166. /// <param name="sessionManager">The session manager.</param>
  167. public SessionsService(ISessionManager sessionManager, IDtoService dtoService)
  168. {
  169. _sessionManager = sessionManager;
  170. _dtoService = dtoService;
  171. }
  172. /// <summary>
  173. /// Gets the specified request.
  174. /// </summary>
  175. /// <param name="request">The request.</param>
  176. /// <returns>System.Object.</returns>
  177. public object Get(GetSessions request)
  178. {
  179. var result = _sessionManager.Sessions.Where(i => i.IsActive);
  180. if (request.SupportsRemoteControl.HasValue)
  181. {
  182. result = result.Where(i => i.SupportsRemoteControl == request.SupportsRemoteControl.Value);
  183. }
  184. return ToOptimizedResult(result.Select(_dtoService.GetSessionInfoDto).ToList());
  185. }
  186. public void Post(SendPlaystateCommand request)
  187. {
  188. var task = SendPlaystateCommand(request);
  189. Task.WaitAll(task);
  190. }
  191. private async Task SendPlaystateCommand(SendPlaystateCommand request)
  192. {
  193. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  194. if (session == null)
  195. {
  196. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  197. }
  198. if (!session.SupportsRemoteControl)
  199. {
  200. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  201. }
  202. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  203. if (socket != null)
  204. {
  205. try
  206. {
  207. await socket.SendAsync(new WebSocketMessage<PlaystateRequest>
  208. {
  209. MessageType = "Playstate",
  210. Data = new PlaystateRequest
  211. {
  212. Command = request.Command,
  213. SeekPositionTicks = request.SeekPositionTicks
  214. }
  215. }, CancellationToken.None).ConfigureAwait(false);
  216. }
  217. catch (Exception ex)
  218. {
  219. Logger.ErrorException("Error sending web socket message", ex);
  220. }
  221. }
  222. else
  223. {
  224. throw new InvalidOperationException("The requested session does not have an open web socket.");
  225. }
  226. }
  227. /// <summary>
  228. /// Posts the specified request.
  229. /// </summary>
  230. /// <param name="request">The request.</param>
  231. public void Post(BrowseTo request)
  232. {
  233. var task = BrowseTo(request);
  234. Task.WaitAll(task);
  235. }
  236. /// <summary>
  237. /// Browses to.
  238. /// </summary>
  239. /// <param name="request">The request.</param>
  240. /// <returns>Task.</returns>
  241. /// <exception cref="ResourceNotFoundException"></exception>
  242. /// <exception cref="System.ArgumentException"></exception>
  243. /// <exception cref="System.InvalidOperationException">The requested session does not have an open web socket.</exception>
  244. private async Task BrowseTo(BrowseTo request)
  245. {
  246. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  247. if (session == null)
  248. {
  249. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  250. }
  251. if (!session.SupportsRemoteControl)
  252. {
  253. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  254. }
  255. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  256. if (socket != null)
  257. {
  258. try
  259. {
  260. await socket.SendAsync(new WebSocketMessage<BrowseTo>
  261. {
  262. MessageType = "Browse",
  263. Data = request
  264. }, CancellationToken.None).ConfigureAwait(false);
  265. }
  266. catch (Exception ex)
  267. {
  268. Logger.ErrorException("Error sending web socket message", ex);
  269. }
  270. }
  271. else
  272. {
  273. throw new InvalidOperationException("The requested session does not have an open web socket.");
  274. }
  275. }
  276. /// <summary>
  277. /// Posts the specified request.
  278. /// </summary>
  279. /// <param name="request">The request.</param>
  280. public void Post(SendSystemCommand request)
  281. {
  282. var task = SendSystemCommand(request);
  283. Task.WaitAll(task);
  284. }
  285. private async Task SendSystemCommand(SendSystemCommand request)
  286. {
  287. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  288. if (session == null)
  289. {
  290. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  291. }
  292. if (!session.SupportsRemoteControl)
  293. {
  294. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  295. }
  296. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  297. if (socket != null)
  298. {
  299. try
  300. {
  301. await socket.SendAsync(new WebSocketMessage<string>
  302. {
  303. MessageType = "SystemCommand",
  304. Data = request.Command.ToString()
  305. }, CancellationToken.None).ConfigureAwait(false);
  306. }
  307. catch (Exception ex)
  308. {
  309. Logger.ErrorException("Error sending web socket message", ex);
  310. }
  311. }
  312. else
  313. {
  314. throw new InvalidOperationException("The requested session does not have an open web socket.");
  315. }
  316. }
  317. /// <summary>
  318. /// Posts the specified request.
  319. /// </summary>
  320. /// <param name="request">The request.</param>
  321. public void Post(SendMessageCommand request)
  322. {
  323. var task = SendMessageCommand(request);
  324. Task.WaitAll(task);
  325. }
  326. private async Task SendMessageCommand(SendMessageCommand request)
  327. {
  328. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  329. if (session == null)
  330. {
  331. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  332. }
  333. if (!session.SupportsRemoteControl)
  334. {
  335. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  336. }
  337. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  338. if (socket != null)
  339. {
  340. try
  341. {
  342. await socket.SendAsync(new WebSocketMessage<MessageCommand>
  343. {
  344. MessageType = "MessageCommand",
  345. Data = new MessageCommand
  346. {
  347. Header = string.IsNullOrEmpty(request.Header) ? "Message from Server" : request.Header,
  348. TimeoutMs = request.TimeoutMs,
  349. Text = request.Text
  350. }
  351. }, CancellationToken.None).ConfigureAwait(false);
  352. }
  353. catch (Exception ex)
  354. {
  355. Logger.ErrorException("Error sending web socket message", ex);
  356. }
  357. }
  358. else
  359. {
  360. throw new InvalidOperationException("The requested session does not have an open web socket.");
  361. }
  362. }
  363. /// <summary>
  364. /// Posts the specified request.
  365. /// </summary>
  366. /// <param name="request">The request.</param>
  367. public void Post(Play request)
  368. {
  369. var task = Play(request);
  370. Task.WaitAll(task);
  371. }
  372. /// <summary>
  373. /// Plays the specified request.
  374. /// </summary>
  375. /// <param name="request">The request.</param>
  376. /// <returns>Task.</returns>
  377. /// <exception cref="ResourceNotFoundException"></exception>
  378. /// <exception cref="System.ArgumentException"></exception>
  379. /// <exception cref="System.InvalidOperationException">The requested session does not have an open web socket.</exception>
  380. private async Task Play(Play request)
  381. {
  382. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  383. if (session == null)
  384. {
  385. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  386. }
  387. if (!session.SupportsRemoteControl)
  388. {
  389. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  390. }
  391. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  392. if (socket != null)
  393. {
  394. try
  395. {
  396. await socket.SendAsync(new WebSocketMessage<PlayRequest>
  397. {
  398. MessageType = "Play",
  399. Data = new PlayRequest
  400. {
  401. ItemIds = request.ItemIds.Split(',').ToArray(),
  402. PlayCommand = request.PlayCommand,
  403. StartPositionTicks = request.StartPositionTicks
  404. }
  405. }, CancellationToken.None).ConfigureAwait(false);
  406. }
  407. catch (Exception ex)
  408. {
  409. Logger.ErrorException("Error sending web socket message", ex);
  410. }
  411. }
  412. else
  413. {
  414. throw new InvalidOperationException("The requested session does not have an open web socket.");
  415. }
  416. }
  417. }
  418. }