SessionsService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. /// <summary>
  120. /// Class SessionsService
  121. /// </summary>
  122. public class SessionsService : BaseApiService
  123. {
  124. /// <summary>
  125. /// The _session manager
  126. /// </summary>
  127. private readonly ISessionManager _sessionManager;
  128. /// <summary>
  129. /// Initializes a new instance of the <see cref="SessionsService" /> class.
  130. /// </summary>
  131. /// <param name="sessionManager">The session manager.</param>
  132. public SessionsService(ISessionManager sessionManager)
  133. {
  134. _sessionManager = sessionManager;
  135. }
  136. /// <summary>
  137. /// Gets the specified request.
  138. /// </summary>
  139. /// <param name="request">The request.</param>
  140. /// <returns>System.Object.</returns>
  141. public object Get(GetSessions request)
  142. {
  143. var result = _sessionManager.Sessions.Where(i => i.IsActive);
  144. if (request.SupportsRemoteControl.HasValue)
  145. {
  146. result = result.Where(i => i.SupportsRemoteControl == request.SupportsRemoteControl.Value);
  147. }
  148. return ToOptimizedResult(result.Select(SessionInfoDtoBuilder.GetSessionInfoDto).ToList());
  149. }
  150. public void Post(SendPlaystateCommand request)
  151. {
  152. var task = SendPlaystateCommand(request);
  153. Task.WaitAll(task);
  154. }
  155. private async Task SendPlaystateCommand(SendPlaystateCommand request)
  156. {
  157. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  158. if (session == null)
  159. {
  160. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  161. }
  162. if (!session.SupportsRemoteControl)
  163. {
  164. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  165. }
  166. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  167. if (socket != null)
  168. {
  169. try
  170. {
  171. await socket.SendAsync(new WebSocketMessage<PlaystateRequest>
  172. {
  173. MessageType = "Playstate",
  174. Data = new PlaystateRequest
  175. {
  176. Command = request.Command,
  177. SeekPositionTicks = request.SeekPositionTicks
  178. }
  179. }, CancellationToken.None).ConfigureAwait(false);
  180. }
  181. catch (Exception ex)
  182. {
  183. Logger.ErrorException("Error sending web socket message", ex);
  184. }
  185. }
  186. else
  187. {
  188. throw new InvalidOperationException("The requested session does not have an open web socket.");
  189. }
  190. }
  191. /// <summary>
  192. /// Posts the specified request.
  193. /// </summary>
  194. /// <param name="request">The request.</param>
  195. public void Post(BrowseTo request)
  196. {
  197. var task = BrowseTo(request);
  198. Task.WaitAll(task);
  199. }
  200. /// <summary>
  201. /// Browses to.
  202. /// </summary>
  203. /// <param name="request">The request.</param>
  204. /// <returns>Task.</returns>
  205. /// <exception cref="ResourceNotFoundException"></exception>
  206. /// <exception cref="System.ArgumentException"></exception>
  207. /// <exception cref="System.InvalidOperationException">The requested session does not have an open web socket.</exception>
  208. private async Task BrowseTo(BrowseTo request)
  209. {
  210. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  211. if (session == null)
  212. {
  213. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  214. }
  215. if (!session.SupportsRemoteControl)
  216. {
  217. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  218. }
  219. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  220. if (socket != null)
  221. {
  222. try
  223. {
  224. await socket.SendAsync(new WebSocketMessage<BrowseTo>
  225. {
  226. MessageType = "Browse",
  227. Data = request
  228. }, CancellationToken.None).ConfigureAwait(false);
  229. }
  230. catch (Exception ex)
  231. {
  232. Logger.ErrorException("Error sending web socket message", ex);
  233. }
  234. }
  235. else
  236. {
  237. throw new InvalidOperationException("The requested session does not have an open web socket.");
  238. }
  239. }
  240. /// <summary>
  241. /// Posts the specified request.
  242. /// </summary>
  243. /// <param name="request">The request.</param>
  244. public void Post(Play request)
  245. {
  246. var task = Play(request);
  247. Task.WaitAll(task);
  248. }
  249. /// <summary>
  250. /// Plays the specified request.
  251. /// </summary>
  252. /// <param name="request">The request.</param>
  253. /// <returns>Task.</returns>
  254. /// <exception cref="ResourceNotFoundException"></exception>
  255. /// <exception cref="System.ArgumentException"></exception>
  256. /// <exception cref="System.InvalidOperationException">The requested session does not have an open web socket.</exception>
  257. private async Task Play(Play request)
  258. {
  259. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  260. if (session == null)
  261. {
  262. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  263. }
  264. if (!session.SupportsRemoteControl)
  265. {
  266. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  267. }
  268. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  269. if (socket != null)
  270. {
  271. try
  272. {
  273. await socket.SendAsync(new WebSocketMessage<PlayRequest>
  274. {
  275. MessageType = "Play",
  276. Data = new PlayRequest
  277. {
  278. ItemIds = request.ItemIds.Split(',').ToArray(),
  279. PlayCommand = request.PlayCommand,
  280. StartPositionTicks = request.StartPositionTicks
  281. }
  282. }, CancellationToken.None).ConfigureAwait(false);
  283. }
  284. catch (Exception ex)
  285. {
  286. Logger.ErrorException("Error sending web socket message", ex);
  287. }
  288. }
  289. else
  290. {
  291. throw new InvalidOperationException("The requested session does not have an open web socket.");
  292. }
  293. }
  294. }
  295. }