SessionWebSocketListener.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Controller.Dto;
  4. using MediaBrowser.Controller.Session;
  5. using MediaBrowser.Model.Logging;
  6. using System;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. namespace MediaBrowser.Server.Implementations.Session
  10. {
  11. /// <summary>
  12. /// Class SessionWebSocketListener
  13. /// </summary>
  14. public class SessionWebSocketListener : IWebSocketListener
  15. {
  16. /// <summary>
  17. /// The _true task result
  18. /// </summary>
  19. private readonly Task _trueTaskResult = Task.FromResult(true);
  20. /// <summary>
  21. /// The _session manager
  22. /// </summary>
  23. private readonly ISessionManager _sessionManager;
  24. /// <summary>
  25. /// The _logger
  26. /// </summary>
  27. private readonly ILogger _logger;
  28. /// <summary>
  29. /// The _dto service
  30. /// </summary>
  31. private readonly IDtoService _dtoService;
  32. private readonly IServerApplicationHost _appHost;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class.
  35. /// </summary>
  36. /// <param name="sessionManager">The session manager.</param>
  37. /// <param name="logManager">The log manager.</param>
  38. /// <param name="dtoService">The dto service.</param>
  39. public SessionWebSocketListener(ISessionManager sessionManager, ILogManager logManager, IDtoService dtoService, IServerApplicationHost appHost)
  40. {
  41. _sessionManager = sessionManager;
  42. _logger = logManager.GetLogger(GetType().Name);
  43. _dtoService = dtoService;
  44. _appHost = appHost;
  45. }
  46. /// <summary>
  47. /// Processes the message.
  48. /// </summary>
  49. /// <param name="message">The message.</param>
  50. /// <returns>Task.</returns>
  51. public Task ProcessMessage(WebSocketMessageInfo message)
  52. {
  53. if (string.Equals(message.MessageType, "Identity", StringComparison.OrdinalIgnoreCase))
  54. {
  55. ProcessIdentityMessage(message);
  56. }
  57. else if (string.Equals(message.MessageType, "Context", StringComparison.OrdinalIgnoreCase))
  58. {
  59. ProcessContextMessage(message);
  60. }
  61. else if (string.Equals(message.MessageType, "PlaybackStart", StringComparison.OrdinalIgnoreCase))
  62. {
  63. ReportPlaybackStart(message);
  64. }
  65. else if (string.Equals(message.MessageType, "PlaybackProgress", StringComparison.OrdinalIgnoreCase))
  66. {
  67. ReportPlaybackProgress(message);
  68. }
  69. else if (string.Equals(message.MessageType, "PlaybackStopped", StringComparison.OrdinalIgnoreCase))
  70. {
  71. ReportPlaybackStopped(message);
  72. }
  73. return _trueTaskResult;
  74. }
  75. /// <summary>
  76. /// Processes the identity message.
  77. /// </summary>
  78. /// <param name="message">The message.</param>
  79. private async void ProcessIdentityMessage(WebSocketMessageInfo message)
  80. {
  81. _logger.Debug("Received Identity message: " + message.Data);
  82. var vals = message.Data.Split('|');
  83. var client = vals[0];
  84. var deviceId = vals[1];
  85. var version = vals[2];
  86. var deviceName = vals.Length > 3 ? vals[3] : string.Empty;
  87. if (!string.IsNullOrEmpty(deviceName))
  88. {
  89. _logger.Debug("Logging session activity");
  90. await _sessionManager.LogSessionActivity(client, version, deviceId, deviceName, null).ConfigureAwait(false);
  91. }
  92. var session = _sessionManager.Sessions
  93. .FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  94. string.Equals(i.Client, client) &&
  95. string.Equals(i.ApplicationVersion, version));
  96. if (session != null)
  97. {
  98. var controller = new WebSocketController(session, _appHost);
  99. controller.Sockets.Add(message.Connection);
  100. session.SessionController = controller;
  101. }
  102. else
  103. {
  104. _logger.Warn("Unable to determine session based on identity message: {0}", message.Data);
  105. }
  106. }
  107. /// <summary>
  108. /// Processes the context message.
  109. /// </summary>
  110. /// <param name="message">The message.</param>
  111. private void ProcessContextMessage(WebSocketMessageInfo message)
  112. {
  113. var session = GetSessionFromMessage(message);
  114. if (session != null)
  115. {
  116. var vals = message.Data.Split('|');
  117. session.NowViewingItemType = vals[0];
  118. session.NowViewingItemId = vals[1];
  119. session.NowViewingItemName = vals[2];
  120. session.NowViewingContext = vals.Length > 3 ? vals[3] : null;
  121. }
  122. }
  123. /// <summary>
  124. /// Gets the session from message.
  125. /// </summary>
  126. /// <param name="message">The message.</param>
  127. /// <returns>SessionInfo.</returns>
  128. private SessionInfo GetSessionFromMessage(WebSocketMessageInfo message)
  129. {
  130. var result = _sessionManager.Sessions.FirstOrDefault(i =>
  131. {
  132. var controller = i.SessionController as WebSocketController;
  133. if (controller != null)
  134. {
  135. if (controller.Sockets.Any(s => s.Id == message.Connection.Id))
  136. {
  137. return true;
  138. }
  139. }
  140. return false;
  141. });
  142. if (result == null)
  143. {
  144. _logger.Error("Unable to find session based on web socket message");
  145. }
  146. return result;
  147. }
  148. /// <summary>
  149. /// Reports the playback start.
  150. /// </summary>
  151. /// <param name="message">The message.</param>
  152. private void ReportPlaybackStart(WebSocketMessageInfo message)
  153. {
  154. _logger.Debug("Received PlaybackStart message");
  155. var session = GetSessionFromMessage(message);
  156. if (session != null && session.User != null)
  157. {
  158. var vals = message.Data.Split('|');
  159. var item = _dtoService.GetItemByDtoId(vals[0]);
  160. var queueableMediaTypes = string.Empty;
  161. var canSeek = true;
  162. if (vals.Length > 1)
  163. {
  164. canSeek = string.Equals(vals[1], "true", StringComparison.OrdinalIgnoreCase);
  165. }
  166. if (vals.Length > 2)
  167. {
  168. queueableMediaTypes = vals[2];
  169. }
  170. var info = new PlaybackInfo
  171. {
  172. CanSeek = canSeek,
  173. Item = item,
  174. SessionId = session.Id,
  175. QueueableMediaTypes = queueableMediaTypes.Split(',').ToList()
  176. };
  177. _sessionManager.OnPlaybackStart(info);
  178. }
  179. }
  180. /// <summary>
  181. /// Reports the playback progress.
  182. /// </summary>
  183. /// <param name="message">The message.</param>
  184. private void ReportPlaybackProgress(WebSocketMessageInfo message)
  185. {
  186. var session = GetSessionFromMessage(message);
  187. if (session != null && session.User != null)
  188. {
  189. var vals = message.Data.Split('|');
  190. var item = _dtoService.GetItemByDtoId(vals[0]);
  191. long? positionTicks = null;
  192. if (vals.Length > 1)
  193. {
  194. long pos;
  195. if (long.TryParse(vals[1], out pos))
  196. {
  197. positionTicks = pos;
  198. }
  199. }
  200. var isPaused = vals.Length > 2 && string.Equals(vals[2], "true", StringComparison.OrdinalIgnoreCase);
  201. var isMuted = vals.Length > 3 && string.Equals(vals[3], "true", StringComparison.OrdinalIgnoreCase);
  202. var info = new PlaybackProgressInfo
  203. {
  204. Item = item,
  205. PositionTicks = positionTicks,
  206. IsMuted = isMuted,
  207. IsPaused = isPaused,
  208. SessionId = session.Id
  209. };
  210. _sessionManager.OnPlaybackProgress(info);
  211. }
  212. }
  213. /// <summary>
  214. /// Reports the playback stopped.
  215. /// </summary>
  216. /// <param name="message">The message.</param>
  217. private void ReportPlaybackStopped(WebSocketMessageInfo message)
  218. {
  219. _logger.Debug("Received PlaybackStopped message");
  220. var session = GetSessionFromMessage(message);
  221. if (session != null && session.User != null)
  222. {
  223. var vals = message.Data.Split('|');
  224. var item = _dtoService.GetItemByDtoId(vals[0]);
  225. long? positionTicks = null;
  226. if (vals.Length > 1)
  227. {
  228. long pos;
  229. if (long.TryParse(vals[1], out pos))
  230. {
  231. positionTicks = pos;
  232. }
  233. }
  234. var info = new PlaybackStopInfo
  235. {
  236. Item = item,
  237. PositionTicks = positionTicks,
  238. SessionId = session.Id
  239. };
  240. _sessionManager.OnPlaybackStopped(info);
  241. }
  242. }
  243. }
  244. }