DlnaEventManager.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Net.Http;
  9. using System.Net.Mime;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using Jellyfin.Extensions;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Common.Net;
  15. using Microsoft.Extensions.Logging;
  16. namespace Emby.Dlna.Eventing
  17. {
  18. public class DlnaEventManager : IDlnaEventManager
  19. {
  20. private readonly ConcurrentDictionary<string, EventSubscription> _subscriptions =
  21. new ConcurrentDictionary<string, EventSubscription>(StringComparer.OrdinalIgnoreCase);
  22. private readonly ILogger _logger;
  23. private readonly IHttpClientFactory _httpClientFactory;
  24. public DlnaEventManager(ILogger logger, IHttpClientFactory httpClientFactory)
  25. {
  26. _httpClientFactory = httpClientFactory;
  27. _logger = logger;
  28. }
  29. public EventSubscriptionResponse RenewEventSubscription(string subscriptionId, string notificationType, string requestedTimeoutString, string callbackUrl)
  30. {
  31. var subscription = GetSubscription(subscriptionId, false);
  32. if (subscription is not null)
  33. {
  34. subscription.TimeoutSeconds = ParseTimeout(requestedTimeoutString) ?? 300;
  35. int timeoutSeconds = subscription.TimeoutSeconds;
  36. subscription.SubscriptionTime = DateTime.UtcNow;
  37. _logger.LogDebug(
  38. "Renewing event subscription for {0} with timeout of {1} to {2}",
  39. subscription.NotificationType,
  40. timeoutSeconds,
  41. subscription.CallbackUrl);
  42. return GetEventSubscriptionResponse(subscriptionId, requestedTimeoutString, timeoutSeconds);
  43. }
  44. return new EventSubscriptionResponse(string.Empty, "text/plain");
  45. }
  46. public EventSubscriptionResponse CreateEventSubscription(string notificationType, string requestedTimeoutString, string callbackUrl)
  47. {
  48. var timeout = ParseTimeout(requestedTimeoutString) ?? 300;
  49. var id = "uuid:" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
  50. _logger.LogDebug(
  51. "Creating event subscription for {0} with timeout of {1} to {2}",
  52. notificationType,
  53. timeout,
  54. callbackUrl);
  55. _subscriptions.TryAdd(id, new EventSubscription
  56. {
  57. Id = id,
  58. CallbackUrl = callbackUrl,
  59. SubscriptionTime = DateTime.UtcNow,
  60. TimeoutSeconds = timeout,
  61. NotificationType = notificationType
  62. });
  63. return GetEventSubscriptionResponse(id, requestedTimeoutString, timeout);
  64. }
  65. private int? ParseTimeout(string header)
  66. {
  67. if (!string.IsNullOrEmpty(header))
  68. {
  69. // Starts with SECOND-
  70. if (int.TryParse(header.AsSpan().RightPart('-'), NumberStyles.Integer, CultureInfo.InvariantCulture, out var val))
  71. {
  72. return val;
  73. }
  74. }
  75. return null;
  76. }
  77. public EventSubscriptionResponse CancelEventSubscription(string subscriptionId)
  78. {
  79. _logger.LogDebug("Cancelling event subscription {0}", subscriptionId);
  80. _subscriptions.TryRemove(subscriptionId, out _);
  81. return new EventSubscriptionResponse(string.Empty, "text/plain");
  82. }
  83. private EventSubscriptionResponse GetEventSubscriptionResponse(string subscriptionId, string requestedTimeoutString, int timeoutSeconds)
  84. {
  85. var response = new EventSubscriptionResponse(string.Empty, "text/plain");
  86. response.Headers["SID"] = subscriptionId;
  87. response.Headers["TIMEOUT"] = string.IsNullOrEmpty(requestedTimeoutString) ? ("SECOND-" + timeoutSeconds.ToString(CultureInfo.InvariantCulture)) : requestedTimeoutString;
  88. return response;
  89. }
  90. public EventSubscription GetSubscription(string id)
  91. {
  92. return GetSubscription(id, false);
  93. }
  94. private EventSubscription GetSubscription(string id, bool throwOnMissing)
  95. {
  96. if (!_subscriptions.TryGetValue(id, out EventSubscription e) && throwOnMissing)
  97. {
  98. throw new ResourceNotFoundException("Event with Id " + id + " not found.");
  99. }
  100. return e;
  101. }
  102. public Task TriggerEvent(string notificationType, IDictionary<string, string> stateVariables)
  103. {
  104. var subs = _subscriptions.Values
  105. .Where(i => !i.IsExpired && string.Equals(notificationType, i.NotificationType, StringComparison.OrdinalIgnoreCase));
  106. var tasks = subs.Select(i => TriggerEvent(i, stateVariables));
  107. return Task.WhenAll(tasks);
  108. }
  109. private async Task TriggerEvent(EventSubscription subscription, IDictionary<string, string> stateVariables)
  110. {
  111. var builder = new StringBuilder();
  112. builder.Append("<?xml version=\"1.0\"?>");
  113. builder.Append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
  114. foreach (var key in stateVariables.Keys)
  115. {
  116. builder.Append("<e:property>")
  117. .Append('<')
  118. .Append(key)
  119. .Append('>')
  120. .Append(stateVariables[key])
  121. .Append("</")
  122. .Append(key)
  123. .Append('>')
  124. .Append("</e:property>");
  125. }
  126. builder.Append("</e:propertyset>");
  127. using var options = new HttpRequestMessage(new HttpMethod("NOTIFY"), subscription.CallbackUrl);
  128. options.Content = new StringContent(builder.ToString(), Encoding.UTF8, MediaTypeNames.Text.Xml);
  129. options.Headers.TryAddWithoutValidation("NT", subscription.NotificationType);
  130. options.Headers.TryAddWithoutValidation("NTS", "upnp:propchange");
  131. options.Headers.TryAddWithoutValidation("SID", subscription.Id);
  132. options.Headers.TryAddWithoutValidation("SEQ", subscription.TriggerCount.ToString(CultureInfo.InvariantCulture));
  133. try
  134. {
  135. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  136. .SendAsync(options, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
  137. }
  138. catch (OperationCanceledException)
  139. {
  140. }
  141. catch
  142. {
  143. // Already logged at lower levels
  144. }
  145. finally
  146. {
  147. subscription.IncrementTriggerCount();
  148. }
  149. }
  150. }
  151. }