EventManager.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Dlna;
  4. using MediaBrowser.Model.Logging;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.Globalization;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace Emby.Dlna.Eventing
  13. {
  14. public class EventManager : IEventManager
  15. {
  16. private readonly ConcurrentDictionary<string, EventSubscription> _subscriptions =
  17. new ConcurrentDictionary<string, EventSubscription>(StringComparer.OrdinalIgnoreCase);
  18. private readonly ILogger _logger;
  19. private readonly IHttpClient _httpClient;
  20. public EventManager(ILogger logger, IHttpClient httpClient)
  21. {
  22. _httpClient = httpClient;
  23. _logger = logger;
  24. }
  25. public EventSubscriptionResponse RenewEventSubscription(string subscriptionId, string requestedTimeoutString)
  26. {
  27. var subscription = GetSubscription(subscriptionId, true);
  28. // Remove logging for now because some devices are sending this very frequently
  29. // TODO re-enable with dlna debug logging setting
  30. //_logger.Debug("Renewing event subscription for {0} with timeout of {1} to {2}",
  31. // subscription.NotificationType,
  32. // timeout,
  33. // subscription.CallbackUrl);
  34. subscription.TimeoutSeconds = ParseTimeout(requestedTimeoutString) ?? 300;
  35. subscription.SubscriptionTime = DateTime.UtcNow;
  36. return GetEventSubscriptionResponse(subscriptionId, requestedTimeoutString, subscription.TimeoutSeconds);
  37. }
  38. public EventSubscriptionResponse CreateEventSubscription(string notificationType, string requestedTimeoutString, string callbackUrl)
  39. {
  40. var timeout = ParseTimeout(requestedTimeoutString) ?? 300;
  41. var id = "uuid:" + Guid.NewGuid().ToString("N");
  42. // Remove logging for now because some devices are sending this very frequently
  43. // TODO re-enable with dlna debug logging setting
  44. //_logger.Debug("Creating event subscription for {0} with timeout of {1} to {2}",
  45. // notificationType,
  46. // timeout,
  47. // callbackUrl);
  48. _subscriptions.TryAdd(id, new EventSubscription
  49. {
  50. Id = id,
  51. CallbackUrl = callbackUrl,
  52. SubscriptionTime = DateTime.UtcNow,
  53. TimeoutSeconds = timeout
  54. });
  55. return GetEventSubscriptionResponse(id, requestedTimeoutString, timeout);
  56. }
  57. private int? ParseTimeout(string header)
  58. {
  59. if (!string.IsNullOrEmpty(header))
  60. {
  61. // Starts with SECOND-
  62. header = header.Split('-').Last();
  63. int val;
  64. if (int.TryParse(header, NumberStyles.Any, _usCulture, out val))
  65. {
  66. return val;
  67. }
  68. }
  69. return null;
  70. }
  71. public EventSubscriptionResponse CancelEventSubscription(string subscriptionId)
  72. {
  73. _logger.Debug("Cancelling event subscription {0}", subscriptionId);
  74. EventSubscription sub;
  75. _subscriptions.TryRemove(subscriptionId, out sub);
  76. return new EventSubscriptionResponse
  77. {
  78. Content = string.Empty,
  79. ContentType = "text/plain"
  80. };
  81. }
  82. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  83. private EventSubscriptionResponse GetEventSubscriptionResponse(string subscriptionId, string requestedTimeoutString, int timeoutSeconds)
  84. {
  85. var response = new EventSubscriptionResponse
  86. {
  87. Content = string.Empty,
  88. ContentType = "text/plain"
  89. };
  90. response.Headers["SID"] = subscriptionId;
  91. response.Headers["TIMEOUT"] = string.IsNullOrWhiteSpace(requestedTimeoutString) ? ("SECOND-" + timeoutSeconds.ToString(_usCulture)) : requestedTimeoutString;
  92. return response;
  93. }
  94. public EventSubscription GetSubscription(string id)
  95. {
  96. return GetSubscription(id, false);
  97. }
  98. private EventSubscription GetSubscription(string id, bool throwOnMissing)
  99. {
  100. EventSubscription e;
  101. if (!_subscriptions.TryGetValue(id, out e) && throwOnMissing)
  102. {
  103. throw new ResourceNotFoundException("Event with Id " + id + " not found.");
  104. }
  105. return e;
  106. }
  107. public Task TriggerEvent(string notificationType, IDictionary<string, string> stateVariables)
  108. {
  109. var subs = _subscriptions.Values
  110. .Where(i => !i.IsExpired && string.Equals(notificationType, i.NotificationType, StringComparison.OrdinalIgnoreCase))
  111. .ToList();
  112. var tasks = subs.Select(i => TriggerEvent(i, stateVariables));
  113. return Task.WhenAll(tasks);
  114. }
  115. private async Task TriggerEvent(EventSubscription subscription, IDictionary<string, string> stateVariables)
  116. {
  117. var builder = new StringBuilder();
  118. builder.Append("<?xml version=\"1.0\"?>");
  119. builder.Append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
  120. foreach (var key in stateVariables.Keys)
  121. {
  122. builder.Append("<e:property>");
  123. builder.Append("<" + key + ">");
  124. builder.Append(stateVariables[key]);
  125. builder.Append("</" + key + ">");
  126. builder.Append("</e:property>");
  127. }
  128. builder.Append("</e:propertyset>");
  129. var options = new HttpRequestOptions
  130. {
  131. RequestContent = builder.ToString(),
  132. RequestContentType = "text/xml",
  133. Url = subscription.CallbackUrl,
  134. BufferContent = false
  135. };
  136. options.RequestHeaders.Add("NT", subscription.NotificationType);
  137. options.RequestHeaders.Add("NTS", "upnp:propchange");
  138. options.RequestHeaders.Add("SID", subscription.Id);
  139. options.RequestHeaders.Add("SEQ", subscription.TriggerCount.ToString(_usCulture));
  140. try
  141. {
  142. await _httpClient.SendAsync(options, "NOTIFY").ConfigureAwait(false);
  143. }
  144. catch (OperationCanceledException)
  145. {
  146. }
  147. catch
  148. {
  149. // Already logged at lower levels
  150. }
  151. finally
  152. {
  153. subscription.IncrementTriggerCount();
  154. }
  155. }
  156. }
  157. }