SessionsService.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Dto;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Session;
  5. using MediaBrowser.Model.Net;
  6. using MediaBrowser.Model.Session;
  7. using ServiceStack.ServiceHost;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Api
  14. {
  15. /// <summary>
  16. /// Class GetSessions
  17. /// </summary>
  18. [Route("/Sessions", "GET")]
  19. [Api(("Gets a list of sessions"))]
  20. public class GetSessions : IReturn<List<SessionInfoDto>>
  21. {
  22. /// <summary>
  23. /// Gets or sets a value indicating whether [supports remote control].
  24. /// </summary>
  25. /// <value><c>null</c> if [supports remote control] contains no value, <c>true</c> if [supports remote control]; otherwise, <c>false</c>.</value>
  26. [ApiMember(Name = "SupportsRemoteControl", Description = "Optional. Filter by sessions that can be remote controlled.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
  27. public bool? SupportsRemoteControl { get; set; }
  28. }
  29. /// <summary>
  30. /// Class BrowseTo
  31. /// </summary>
  32. [Route("/Sessions/{Id}/Viewing", "POST")]
  33. [Api(("Instructs a session to browse to an item or view"))]
  34. public class BrowseTo : IReturnVoid
  35. {
  36. /// <summary>
  37. /// Gets or sets the id.
  38. /// </summary>
  39. /// <value>The id.</value>
  40. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  41. public Guid Id { get; set; }
  42. /// <summary>
  43. /// Artist, Genre, Studio, Person, or any kind of BaseItem
  44. /// </summary>
  45. /// <value>The type of the item.</value>
  46. [ApiMember(Name = "ItemType", Description = "The type of item to browse to.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  47. public string ItemType { get; set; }
  48. /// <summary>
  49. /// Artist name, genre name, item Id, etc
  50. /// </summary>
  51. /// <value>The item identifier.</value>
  52. [ApiMember(Name = "ItemId", Description = "The Id of the item.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  53. public string ItemId { get; set; }
  54. /// <summary>
  55. /// Gets or sets the name of the item.
  56. /// </summary>
  57. /// <value>The name of the item.</value>
  58. [ApiMember(Name = "ItemName", Description = "The name of the item.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  59. public string ItemName { get; set; }
  60. /// <summary>
  61. /// Gets or sets the context (Movies, Music, TvShows, etc)
  62. /// Applicable to genres, studios and persons only because the context of items and artists can be inferred.
  63. /// This is optional to supply and clients are free to ignore it.
  64. /// </summary>
  65. /// <value>The context.</value>
  66. [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")]
  67. public string Context { get; set; }
  68. }
  69. [Route("/Sessions/{Id}/Playing", "POST")]
  70. [Api(("Instructs a session to play an item"))]
  71. public class Play : IReturnVoid
  72. {
  73. /// <summary>
  74. /// Gets or sets the id.
  75. /// </summary>
  76. /// <value>The id.</value>
  77. [ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  78. public Guid Id { get; set; }
  79. /// <summary>
  80. /// Artist, Genre, Studio, Person, or any kind of BaseItem
  81. /// </summary>
  82. /// <value>The type of the item.</value>
  83. [ApiMember(Name = "ItemIds", Description = "The ids of the items to play, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)]
  84. public string ItemIds { get; set; }
  85. /// <summary>
  86. /// Gets or sets the start position ticks that the first item should be played at
  87. /// </summary>
  88. /// <value>The start position ticks.</value>
  89. [ApiMember(Name = "StartPositionTicks", Description = "The starting position of the first item.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
  90. public long? StartPositionTicks { get; set; }
  91. /// <summary>
  92. /// Gets or sets the play command.
  93. /// </summary>
  94. /// <value>The play command.</value>
  95. [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")]
  96. public PlayCommand PlayCommand { get; set; }
  97. }
  98. /// <summary>
  99. /// Class SessionsService
  100. /// </summary>
  101. public class SessionsService : BaseApiService
  102. {
  103. /// <summary>
  104. /// The _session manager
  105. /// </summary>
  106. private readonly ISessionManager _sessionManager;
  107. /// <summary>
  108. /// Initializes a new instance of the <see cref="SessionsService" /> class.
  109. /// </summary>
  110. /// <param name="sessionManager">The session manager.</param>
  111. public SessionsService(ISessionManager sessionManager)
  112. {
  113. _sessionManager = sessionManager;
  114. }
  115. /// <summary>
  116. /// Gets the specified request.
  117. /// </summary>
  118. /// <param name="request">The request.</param>
  119. /// <returns>System.Object.</returns>
  120. public object Get(GetSessions request)
  121. {
  122. var result = _sessionManager.Sessions.Where(i => i.IsActive);
  123. if (request.SupportsRemoteControl.HasValue)
  124. {
  125. result = result.Where(i => i.SupportsRemoteControl == request.SupportsRemoteControl.Value);
  126. }
  127. return ToOptimizedResult(result.Select(SessionInfoDtoBuilder.GetSessionInfoDto).ToList());
  128. }
  129. /// <summary>
  130. /// Posts the specified request.
  131. /// </summary>
  132. /// <param name="request">The request.</param>
  133. public void Post(BrowseTo request)
  134. {
  135. var task = BrowseTo(request);
  136. Task.WaitAll(task);
  137. }
  138. /// <summary>
  139. /// Browses to.
  140. /// </summary>
  141. /// <param name="request">The request.</param>
  142. /// <returns>Task.</returns>
  143. /// <exception cref="ResourceNotFoundException"></exception>
  144. /// <exception cref="System.ArgumentException"></exception>
  145. /// <exception cref="System.InvalidOperationException">The requested session does not have an open web socket.</exception>
  146. private async Task BrowseTo(BrowseTo request)
  147. {
  148. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  149. if (session == null)
  150. {
  151. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  152. }
  153. if (!session.SupportsRemoteControl)
  154. {
  155. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  156. }
  157. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  158. if (socket != null)
  159. {
  160. try
  161. {
  162. await socket.SendAsync(new WebSocketMessage<BrowseTo>
  163. {
  164. MessageType = "Browse",
  165. Data = request
  166. }, CancellationToken.None).ConfigureAwait(false);
  167. }
  168. catch (Exception ex)
  169. {
  170. Logger.ErrorException("Error sending web socket message", ex);
  171. }
  172. }
  173. else
  174. {
  175. throw new InvalidOperationException("The requested session does not have an open web socket.");
  176. }
  177. }
  178. /// <summary>
  179. /// Posts the specified request.
  180. /// </summary>
  181. /// <param name="request">The request.</param>
  182. public void Post(Play request)
  183. {
  184. var task = Play(request);
  185. Task.WaitAll(task);
  186. }
  187. /// <summary>
  188. /// Plays the specified request.
  189. /// </summary>
  190. /// <param name="request">The request.</param>
  191. /// <returns>Task.</returns>
  192. /// <exception cref="ResourceNotFoundException"></exception>
  193. /// <exception cref="System.ArgumentException"></exception>
  194. /// <exception cref="System.InvalidOperationException">The requested session does not have an open web socket.</exception>
  195. private async Task Play(Play request)
  196. {
  197. var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
  198. if (session == null)
  199. {
  200. throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
  201. }
  202. if (!session.SupportsRemoteControl)
  203. {
  204. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  205. }
  206. var socket = session.WebSockets.OrderByDescending(i => i.LastActivityDate).FirstOrDefault(i => i.State == WebSocketState.Open);
  207. if (socket != null)
  208. {
  209. try
  210. {
  211. await socket.SendAsync(new WebSocketMessage<PlayRequest>
  212. {
  213. MessageType = "Play",
  214. Data = new PlayRequest
  215. {
  216. ItemIds = request.ItemIds.Split(',').ToArray(),
  217. PlayCommand = request.PlayCommand,
  218. StartPositionTicks = request.StartPositionTicks
  219. }
  220. }, CancellationToken.None).ConfigureAwait(false);
  221. }
  222. catch (Exception ex)
  223. {
  224. Logger.ErrorException("Error sending web socket message", ex);
  225. }
  226. }
  227. else
  228. {
  229. throw new InvalidOperationException("The requested session does not have an open web socket.");
  230. }
  231. }
  232. }
  233. }