EventManager.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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 MediaBrowser.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, int? timeoutSeconds)
  26. {
  27. var timeout = timeoutSeconds ?? 300;
  28. var subscription = GetSubscription(subscriptionId, true);
  29. _logger.Debug("Renewing event subscription for {0} with timeout of {1} to {2}",
  30. subscription.NotificationType,
  31. timeout,
  32. subscription.CallbackUrl);
  33. subscription.TimeoutSeconds = timeout;
  34. subscription.SubscriptionTime = DateTime.UtcNow;
  35. return GetEventSubscriptionResponse(subscriptionId, timeout);
  36. }
  37. public EventSubscriptionResponse CreateEventSubscription(string notificationType, int? timeoutSeconds, string callbackUrl)
  38. {
  39. var timeout = timeoutSeconds ?? 300;
  40. var id = "uuid:" + Guid.NewGuid().ToString("N");
  41. _logger.Debug("Creating event subscription for {0} with timeout of {1} to {2}",
  42. notificationType,
  43. timeout,
  44. callbackUrl);
  45. _subscriptions.TryAdd(id, new EventSubscription
  46. {
  47. Id = id,
  48. CallbackUrl = callbackUrl,
  49. SubscriptionTime = DateTime.UtcNow,
  50. TimeoutSeconds = timeout
  51. });
  52. return GetEventSubscriptionResponse(id, timeout);
  53. }
  54. public EventSubscriptionResponse CancelEventSubscription(string subscriptionId)
  55. {
  56. _logger.Debug("Cancelling event subscription {0}", subscriptionId);
  57. EventSubscription sub;
  58. _subscriptions.TryRemove(subscriptionId, out sub);
  59. return new EventSubscriptionResponse
  60. {
  61. Content = "\r\n",
  62. ContentType = "text/plain"
  63. };
  64. }
  65. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  66. private EventSubscriptionResponse GetEventSubscriptionResponse(string subscriptionId, int timeoutSeconds)
  67. {
  68. var response = new EventSubscriptionResponse
  69. {
  70. Content = "\r\n",
  71. ContentType = "text/plain"
  72. };
  73. response.Headers["SID"] = subscriptionId;
  74. response.Headers["TIMEOUT"] = "SECOND-" + timeoutSeconds.ToString(_usCulture);
  75. return response;
  76. }
  77. public EventSubscription GetSubscription(string id)
  78. {
  79. return GetSubscription(id, false);
  80. }
  81. private EventSubscription GetSubscription(string id, bool throwOnMissing)
  82. {
  83. EventSubscription e;
  84. if (!_subscriptions.TryGetValue(id, out e) && throwOnMissing)
  85. {
  86. throw new ResourceNotFoundException("Event with Id " + id + " not found.");
  87. }
  88. return e;
  89. }
  90. public Task TriggerEvent(string notificationType, IDictionary<string, string> stateVariables)
  91. {
  92. var subs = _subscriptions.Values
  93. .Where(i => !i.IsExpired && string.Equals(notificationType, i.NotificationType, StringComparison.OrdinalIgnoreCase))
  94. .ToList();
  95. var tasks = subs.Select(i => TriggerEvent(i, stateVariables));
  96. return Task.WhenAll(tasks);
  97. }
  98. private async Task TriggerEvent(EventSubscription subscription, IDictionary<string, string> stateVariables)
  99. {
  100. var builder = new StringBuilder();
  101. builder.Append("<?xml version=\"1.0\"?>");
  102. builder.Append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
  103. foreach (var key in stateVariables.Keys)
  104. {
  105. builder.Append("<e:property>");
  106. builder.Append("<" + key + ">");
  107. builder.Append(stateVariables[key]);
  108. builder.Append("</" + key + ">");
  109. builder.Append("</e:property>");
  110. }
  111. builder.Append("</e:propertyset>");
  112. var options = new HttpRequestOptions
  113. {
  114. RequestContent = builder.ToString(),
  115. RequestContentType = "text/xml",
  116. Url = subscription.CallbackUrl,
  117. BufferContent = false
  118. };
  119. options.RequestHeaders.Add("NT", subscription.NotificationType);
  120. options.RequestHeaders.Add("NTS", "upnp:propchange");
  121. options.RequestHeaders.Add("SID", subscription.Id);
  122. options.RequestHeaders.Add("SEQ", subscription.TriggerCount.ToString(_usCulture));
  123. try
  124. {
  125. await _httpClient.SendAsync(options, "NOTIFY").ConfigureAwait(false);
  126. }
  127. catch (OperationCanceledException)
  128. {
  129. }
  130. catch
  131. {
  132. // Already logged at lower levels
  133. }
  134. finally
  135. {
  136. subscription.IncrementTriggerCount();
  137. }
  138. }
  139. }
  140. }