HttpSessionController.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Session;
  3. using MediaBrowser.Model.Entities;
  4. using MediaBrowser.Model.Serialization;
  5. using MediaBrowser.Model.Session;
  6. using MediaBrowser.Model.System;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Server.Implementations.Session
  15. {
  16. public class HttpSessionController : ISessionController, IDisposable
  17. {
  18. private readonly IHttpClient _httpClient;
  19. private readonly IJsonSerializer _json;
  20. private readonly ISessionManager _sessionManager;
  21. public SessionInfo Session { get; private set; }
  22. private readonly string _postUrl;
  23. private Timer _pingTimer;
  24. private DateTime _lastPingTime;
  25. public HttpSessionController(IHttpClient httpClient,
  26. IJsonSerializer json,
  27. SessionInfo session,
  28. string postUrl, ISessionManager sessionManager)
  29. {
  30. _httpClient = httpClient;
  31. _json = json;
  32. Session = session;
  33. _postUrl = postUrl;
  34. _sessionManager = sessionManager;
  35. _pingTimer = new Timer(PingTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
  36. ResetPingTimer();
  37. }
  38. private string PostUrl
  39. {
  40. get
  41. {
  42. return string.Format("http://{0}{1}", Session.RemoteEndPoint, _postUrl);
  43. }
  44. }
  45. public bool IsSessionActive
  46. {
  47. get
  48. {
  49. return (DateTime.UtcNow - Session.LastActivityDate).TotalMinutes <= 20;
  50. }
  51. }
  52. public bool SupportsMediaControl
  53. {
  54. get { return true; }
  55. }
  56. private async void PingTimerCallback(object state)
  57. {
  58. try
  59. {
  60. await SendMessage("Ping", CancellationToken.None).ConfigureAwait(false);
  61. _lastPingTime = DateTime.UtcNow;
  62. }
  63. catch
  64. {
  65. var lastActivityDate = new[] { _lastPingTime, Session.LastActivityDate }
  66. .Max();
  67. var timeSinceLastPing = DateTime.UtcNow - lastActivityDate;
  68. // We don't want to stop the session due to one single request failure
  69. // At the same time, we don't want the timeout to be too long because it will
  70. // be sitting in active sessions available for remote control, when it's not
  71. if (timeSinceLastPing >= TimeSpan.FromMinutes(5))
  72. {
  73. ReportSessionEnded();
  74. }
  75. }
  76. }
  77. private void ReportSessionEnded()
  78. {
  79. try
  80. {
  81. _sessionManager.ReportSessionEnded(Session.Id);
  82. }
  83. catch (Exception ex)
  84. {
  85. }
  86. }
  87. private void ResetPingTimer()
  88. {
  89. if (_pingTimer != null)
  90. {
  91. _lastPingTime = DateTime.UtcNow;
  92. var period = TimeSpan.FromSeconds(60);
  93. _pingTimer.Change(period, period);
  94. }
  95. }
  96. private Task SendMessage(string name, CancellationToken cancellationToken)
  97. {
  98. return SendMessage(name, new Dictionary<string, string>(), cancellationToken);
  99. }
  100. private async Task SendMessage(string name,
  101. Dictionary<string, string> args,
  102. CancellationToken cancellationToken)
  103. {
  104. var url = PostUrl + "/" + name + ToQueryString(args);
  105. await _httpClient.Post(new HttpRequestOptions
  106. {
  107. Url = url,
  108. CancellationToken = cancellationToken
  109. }).ConfigureAwait(false);
  110. ResetPingTimer();
  111. }
  112. public Task SendSessionEndedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
  113. {
  114. return Task.FromResult(true);
  115. }
  116. public Task SendPlaybackStartNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
  117. {
  118. return Task.FromResult(true);
  119. }
  120. public Task SendPlaybackStoppedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
  121. {
  122. return Task.FromResult(true);
  123. }
  124. public Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken)
  125. {
  126. var dict = new Dictionary<string, string>();
  127. dict["ItemIds"] = string.Join(",", command.ItemIds);
  128. if (command.StartPositionTicks.HasValue)
  129. {
  130. dict["StartPositionTicks"] = command.StartPositionTicks.Value.ToString(CultureInfo.InvariantCulture);
  131. }
  132. return SendMessage(command.PlayCommand.ToString(), dict, cancellationToken);
  133. }
  134. public Task SendPlaystateCommand(PlaystateRequest command, CancellationToken cancellationToken)
  135. {
  136. var args = new Dictionary<string, string>();
  137. if (command.Command == PlaystateCommand.Seek)
  138. {
  139. if (!command.SeekPositionTicks.HasValue)
  140. {
  141. throw new ArgumentException("SeekPositionTicks cannot be null");
  142. }
  143. args["SeekPositionTicks"] = command.SeekPositionTicks.Value.ToString(CultureInfo.InvariantCulture);
  144. }
  145. return SendMessage(command.Command.ToString(), args, cancellationToken);
  146. }
  147. public Task SendLibraryUpdateInfo(LibraryUpdateInfo info, CancellationToken cancellationToken)
  148. {
  149. return Task.FromResult(true);
  150. }
  151. public Task SendRestartRequiredNotification(SystemInfo info, CancellationToken cancellationToken)
  152. {
  153. return SendMessage("RestartRequired", cancellationToken);
  154. }
  155. public Task SendUserDataChangeInfo(UserDataChangeInfo info, CancellationToken cancellationToken)
  156. {
  157. return Task.FromResult(true);
  158. }
  159. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  160. {
  161. return SendMessage("ServerShuttingDown", cancellationToken);
  162. }
  163. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  164. {
  165. return SendMessage("ServerRestarting", cancellationToken);
  166. }
  167. public Task SendGeneralCommand(GeneralCommand command, CancellationToken cancellationToken)
  168. {
  169. return SendMessage(command.Name, command.Arguments, cancellationToken);
  170. }
  171. public Task SendMessage<T>(string name, T data, CancellationToken cancellationToken)
  172. {
  173. // Not supported or needed right now
  174. return Task.FromResult(true);
  175. }
  176. private string ToQueryString(Dictionary<string, string> nvc)
  177. {
  178. var array = (from item in nvc
  179. select string.Format("{0}={1}", WebUtility.UrlEncode(item.Key), WebUtility.UrlEncode(item.Value)))
  180. .ToArray();
  181. var args = string.Join("&", array);
  182. if (string.IsNullOrEmpty(args))
  183. {
  184. return args;
  185. }
  186. return "?" + args;
  187. }
  188. public void Dispose()
  189. {
  190. DisposePingTimer();
  191. }
  192. private void DisposePingTimer()
  193. {
  194. if (_pingTimer != null)
  195. {
  196. _pingTimer.Dispose();
  197. _pingTimer = null;
  198. }
  199. }
  200. }
  201. }